[英]Search Multiple Tables of a Mysql Database
我有以下代碼:
$query = "select * from customer where Surname like \"%$trimmed%\" OR TitleName like \"%$trimmed%\" OR PostCode like \"%$trimmed%\"
order by Surname";
但是,我有另一個表,我想用相同的參數(變量)搜索。 我知道像“ select * from customer,othertable
”這樣的東西可能是不可能的,有沒有辦法做到這一點?
通過使用UNION,它可以關閉我的頁面,甚至無法正常搜索
$query = "select * from customer where Surname like \"%$trimmed%\" OR TitleName like \"%$trimmed%\" OR PostCode like \"%$trimmed%\"
order by Surname UNION select * from mooring where Number like \"%$trimmed%\"";
您可以使用UNION
運算符從多個表中進行搜索。
如果表結構不同,則必須使用多個查詢和多個代碼片段來處理不同類型的結果。 或者,您可以使用UNION運算符僅選擇兩個表中的類似字段。 您可以清空不匹配的字段。 考慮一下:
SELECT CustomerID, Surname, PostCode, NULL AS Number, 'CUSTOMER' AS Type
# Suppose that the 'Number' column does not exist in this table
FROM Customer
WHERE Surname LIKE '%$trimmed%'
OR TitleName LIKE '%$trimmed%'
OR PostCode LIKE '%$trimmed%'
UNION
SELECT MooringID, Surname, NULL, Number, 'MOORING'
# Suppose that the 'PostCode' column does not exist in this table
FROM Mooring
WHERE Number LIKE '%$trimmed%'
ORDER BY 2 # ORDER BY goes to the very end of the union query in this case
您的UNION語法不正確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.