当使用union来查询,并分页时

如果数据量很大,很容易造成查询超时,要么就是特别慢

首先我们先分析下数据,是否完全不重复

如果不重复,则使用 union all 

union all和union的区别是,UNION 操作会对结果去重且排序,所以从速度来说, UNION ALL会更胜一筹

接着,所有的条件查询,从子查询入手

例如

  select * from (
    select id from A 
    union all
    select id from B
    ) t
  where t.id>1 limit 10

这时,会从A表查询所有的数据,拼接,查询B表的所有数据,再执行where条件,在分页,查询速度可想而知

优化,从子查询过滤条件

  select * from (
    select id from A  where id>1
    union all
    select id from B where id>1
    ) t limit 10

一定要先筛选再合并数据,这样可以有效的减少数据量,提高查询速度

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2021-10-09
  • 2021-03-28
猜你喜欢
  • 2021-11-29
  • 2022-01-17
  • 2021-08-31
  • 2021-10-06
  • 2021-12-30
  • 2021-07-24
相关资源
相似解决方案