2011-12-09 91 views
3

我願做一個搜索在許多表與如何在許多表格中搜索?

<input type="text" name="search" /> 

$sql = mysql_query("SELECT * FROM cars,people,cities WHERE 
cars.reg= '$search' || people.phone = '$search' || city.address = '$search'"); 

是否有可能做到這一點?有關使用PHP進行數據庫搜索的任何建議?

非常感謝

回答

3

你可以使用UNION ALL查詢

SELECT name as findValue, 
'cars' as tableName 
FROM cars 
where cars.name = "$search" 
UNION ALL 
SELECT name as findValue, 
'people' as tableName 
FROM people 
where people.name = "$search" 
UNION ALL 
SELECT city as findValue, 
'cities' as tableName 
FROM cities 
where cities .name = "$search" 

,你從所有的子查詢返回相同類型的字段是很重要的。有關更多信息,請參閱here,基本上這個想法是,您返回從查詢中找到的所有數據的UNION。

+1

如果您還需要查看結果中每行的來源,則可以爲每個聯合添加一個靜態字段。例如,「汽車」作爲源,「人」作爲源,「城市」作爲源 – jmacinnes

+0

@jmacinnes當然是的,所以你知道數據來自哪裏 –