MySQL搜索在多个表中

时间:2016-05-24 14:11:19

标签: php mysql laravel eloquent

您好我有3个表:城市,地区,子地点,我不知道用户正在搜索哪一个,所以我想一次搜索所有表格,我还需要以某种方式指示是作为结果返回的区域或城市或sub_location。

表格结构:

Cities:
id int
city_name varChar

Areas:
id int
area_name varChar

Sub_locations:
id int
sub_location_name varChar

所以只需要在city_name,area_name和sub_location_name

中搜索

我想使用全文搜索。我也使用Laravel 4,因此您可以在Eloquent中查询。请帮助,以前从未处理过那种逻辑。谢谢。

2 个答案:

答案 0 :(得分:1)

您可以尝试

$keyword = $_POST['your_search_input_field'];

$query = "(SELECT city_name FROM Cities WHERE city_name LIKE '%" . 
       $keyword . "%') 
       UNION
       (SELECT area_name FROM Areas WHERE area_name LIKE '%" . 
       $keyword . "%') 
       UNION
       (SELECT sub_location_name FROM Sub_locations WHERE sub_location_name LIKE '%" . 
       $keyword . "%' )";

mysql_query($query);

答案 1 :(得分:1)

使用此

SELECT `city_name` as `area` ,'city' as type FROM `cities` where city_name 
'your like conditions'
union 
select `area_name` as `area`, 'area' as type from `areas` where 'your like conditions'
union
select `sub_location_name` as `area`, 'sublocation' as type where 'your like conditions'
from `Sub_locations` 

在这里,您可以找到结果,并根据类型列对这些结果进行排序。