【问题标题】:MySQL: select * from multiple tables where column1 or column2 = queryMySQL:从多个表中选择 *,其中 column1 或 column2 = 查询
【发布时间】:2017-03-28 14:06:57
【问题描述】:

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

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

每个表都包含以下列:

  • id、品牌、型号

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

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

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

【问题讨论】:

  • 这是一个非常糟糕的表设计,如果将其标准化,查询会容易得多。但你应该看看UNION
  • @Siyual 是的,我知道这是糟糕的设计,这只是一个了解其工作原理的示例。在实际情况中,我当然会使用单个表,其中“类型”列设置为 pc、笔记本电脑、平板电脑或智能手机。还是谢谢你。

标签: mysql sql select search multiple-tables


【解决方案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%';

但是,这会实现子查询,从而产生额外的开销。

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

【讨论】:

  • 作为补充说明,如果这些表中的任何一个具有不同顺序的字段、额外的字段或联合字段之间的数据类型不兼容,则在使用 UNION ALL 时会遇到错误。跨度>
【解决方案2】:

让我们试试这个 它会起作用的。

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%'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2011-01-29
    • 2021-06-06
    • 1970-01-01
    • 2021-01-30
    • 2016-01-20
    • 2016-01-13
    相关资源
    最近更新 更多