简体   繁体   English

MySQL搜索多个表

[英]MySQL search In multiple tables

Hi I have 3 tables: cities , areas , sub_locations, I don't know which one the user is searching so I'd like to search in all the tables at once and also I need to somehow indicate is it area or city or sub_location that returned as a result. 嗨,我有3个表:city,area,sub_locations,我不知道用户要搜索哪个表,所以我想一次在所有表中搜索,而且我还需要以某种方式指出它是area还是city或sub_location。结果返回。

tables stucture: 表结构:

Cities:
id int
city_name varChar

Areas:
id int
area_name varChar

Sub_locations:
id int
sub_location_name varChar

so only need to search in city_name , area_name and sub_location_name 因此只需要搜索city_name,area_name和sub_location_name

I'd like to use full text search.Also I use Laravel 4 so you may query in Eloquent. 我想使用全文搜索。我也使用Laravel 4,因此您可以用Eloquent查询。 Pls help, never have dealt with that kind of logic before. 请帮助,以前从来没有处理过这种逻辑。 Thank You. 谢谢。

You can try like 你可以尝试像

$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);

Use this 用这个

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` 

Here you will find results and also sort from which table these results coming from by type column . 在这里,您将找到结果,并按列类型对这些结果进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM