[英]PHP/MySQL - Select RANDOM value from column where another column equals value
[英]SELECT from multiple tables where php variable equals a column value
我有一個等於電話號碼值的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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.