如何在许多表中搜索?

时间:2022-06-22 10:17:58

I would like to do a search in many tables with a

我想用a搜索很多表

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

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

Is it possible to do that? any suggestions for that a DB search with PHP?

有可能吗?对于用PHP进行DB搜索有什么建议吗?

Thanks a lot

非常感谢

1 个解决方案

#1


3  

You could use a UNION ALL query

您可以使用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"

It's important that you return the same type of field from all the subqueries. Read here for more info, basically the idea is that you return a UNION of all data found from the queries.

从所有子查询返回相同类型的字段是很重要的。在这里阅读更多信息,基本的想法是返回查询中找到的所有数据的联合。

#1


3  

You could use a UNION ALL query

您可以使用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"

It's important that you return the same type of field from all the subqueries. Read here for more info, basically the idea is that you return a UNION of all data found from the queries.

从所有子查询返回相同类型的字段是很重要的。在这里阅读更多信息,基本的想法是返回查询中找到的所有数据的联合。