我有一个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/