SQL代码如下:select A.*,B.*
from 
   (
  select * from C  where ...
  union all
  select * from D  where ...
) A left join
   B on B.id = A.id
where A.type = 1 and B.format = 2
order by B.num
limit 1,100
先要进行2个表的union操作,然后在join到B表上,对这个结果进行过滤后,再进行排序分页查询,排序字段不固定上面的这个查询SQL貌似就永不到表的索引了。C 表几千的数据,D表几百的数据,B表10W以内的数量。测试的时候发现SQL执行比较慢,求助这个SQL要怎么优化,或者是怎么建立索引能够加速查询效率。

解决方案 »

  1.   

    尝试一下先left join,然后再union all
      

  2.   

    把 A.type = 1放到union all里面的两个select的查询条件里面去, 先尽可能多的过滤掉C、D表的数据, 再join B表查询
    select A.*,B.*
    from 
       (
          select * from C  where type = 1 and ...
          union all
          select * from D  where type = 1 and ...
        ) A left join
       B on B.id = A.id
    where B.format = 2
    order by B.num
    limit 1,100
    还有就是索引, 你可以explain看看sql的执行计划