MySQL:从多个表中选择*,其中column1或column2 = query

时间:2017-03-28 14:06:57

标签: mysql sql select search multiple-tables

假设我有一个包含4个表的数据库:

  • 个人电脑,笔记本电脑,平板电脑,智能手机

这些表中的每一个都包含以下列:

  • id,品牌,型号

如何使用单个查询显示基于用户键入的品牌或型号的所有表格中的所有结果?在伪代码中,类似这样的东西:

 SELECT * 
 FROM   {all tables} 
 WHERE  {brand or model} LIKE %user_search%;

这样用户就可以通过键入品牌或型号来搜索任何设备。例如。键入 apple 将显示所有Apple智能手机和平板电脑。键入型号将显示具有该型号的所有设备,即使是来自不同品牌的设备也是如此。

2 个答案:

答案 0 :(得分:1)

在MySQL中,最好的方法是独立运行每个查询并使用union all

SELECT * FROM t1 WHERE brand LIKE '%user_search%' OR model LIKE '%user_search%'
UNION ALL
SELECT * FROM t2 WHERE brand LIKE '%user_search%' OR model LIKE '%user_search%'
UNION ALL
SELECT * FROM t3 WHERE brand LIKE '%user_search%' OR model LIKE '%user_search%'
UNION ALL
SELECT * FROM t4 WHERE brand LIKE '%user_search%' OR model LIKE '%user_search%';

很有可能将其写成:

select *
from ((select * from t1) union all
      (select * from t2) union all
      (select * from t3) union all
      (select * from t4) 
     ) t
where brand like '%user_search%' or model like '%user_search%';

但是,这会使子查询具体化,从而产生额外的开销。

此外,如果性能有问题,您可能需要考虑全文索引。

答案 1 :(得分:0)

让我们试试吧 它会起作用。

SELECT * from (SELECT * FROM pcs as p 
    UNION
    SELECT * FROM laptops as l 
    UNION
    SELECT * FROM tablets as T ) as tt WHERE tt.brand or tt.model LIKE '%sams%'

它也可以。

SELECT * FROM pcs as p WHERE brand or model LIKE '%sams%'
UNION
SELECT * FROM laptops as l WHERE brand or model LIKE '%sams%'
UNION
SELECT * FROM tablets as t WHERE brand or model LIKE '%sams%'
UNION
SELECT * FROM smartphones as s WHERE brand or model LIKE '%sams%'