我如何在许多表中搜索?

时间:2011-12-09 15:28:53

标签: php mysql sql

我想在许多表格中搜索

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

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

有可能吗?有关使用PHP进行数据库搜索的任何建议吗?

非常感谢

1 个答案:

答案 0 :(得分: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。