我有一个等于电话号码值的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"];
}
但是认为使用像join或union这样的东西可能更好?
答案 0 :(得分:0)
如果您只从每张桌子中选择所需的电话号码,可以使用UNION
将它们放入一张表中像MySQL这样的东西(你可以把它转换成PHP)
(SELECT phone_number FROM t1 WHERE company = $yourvariable)
UNION
(SELECT phone_number FROM t2 WHERE phone_number = $yourvariable)