php - 从多个表中选择,其中 php 变量等于列值

标签 php mysql sql

我有一个等于电话号码值的 php 变量。

我希望能够从多个表中进行选择,其中列等于该变量

最好的方法是什么,我尝试过:

//first select the company
$stmt = $pdo_conn->prepare("SELECT * from customer where phone = :phone ");
$stmt->execute(array(':phone' => $res));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($records) > 0) {
    $caller = $records[0]["company"];
}
elseif(count($records) == 0) {
    //otherwise check contacts
    $stmt = $pdo_conn->prepare("SELECT * from contacts where phone = :phone or mobile = :mobile ");
    $stmt->execute(array(':phone' => $res, ':mobile' => $res));
    $records = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $caller = $records[0]["forename"];
}

但认为使用连接或联合之类的东西可能更好?

最佳答案

如果您仅从每个表中选择所需的电话号码,则可以使用 UNION 将它们放入一个表中

像 MySQL 这样的东西(你可以将它转换为 PHP)

(SELECT phone_number FROM t1 WHERE company = $yourvariable)
UNION
(SELECT phone_number FROM t2 WHERE phone_number = $yourvariable)

关于php - 从多个表中选择,其中 php 变量等于列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22843046/

相关文章:

php - HTML 显示和 MySQL 数据类型

php - 检查 Laravel 中的 session 超时

php - MySQL, PHP 传递 ORDER BY 参数

sql - 如何转换sqlite表中列的日期格式?

sql - SQL Server T SQL 脚本如何判断它具有哪些安全权限?

java - JPA (Hibernate)/QueryDSL left join with condition 不起作用

php - 使用php批量遍历数组

MYSQL - 从一个表中查找另一个表中不存在的记录

c# - 比较来自 Mysql 的 C# 中的两个日期

php - 准备好的语句并检索选定的值