首页 > 数据库技术 > 详细

SQL优化例子

时间:2018-10-23 19:17:53      阅读:114      评论:0      收藏:0      [点我收藏+]
如下SQL的优化:
select count(*) from (
select id,name,col1,col2 from t1  where name=‘xxxx‘
union
select id,name ,null as col1,‘‘ as col2 from t2  where id!=1
)
原SQL慢原因:由于union需要过滤 重复记录。所以会有后台的一个group by id,name,col1,col2的操作。
优化:去掉group by。统计出 t1表,t2 表。去除重复记录的次数
优化后:
select sum(a)-sum(dis) from
(
SELECT  count(*) as a ,0 as dis  FROM t1 a where name=‘xxxx‘
union all
SELECT  count(*) as a,0 as dis  FROM  t2 b WHERE status !=8
union all
select 0 as a, count(1) as dis from  t1 a inner join t2 b a.id=b.id and a.name=b.name where a.name=‘xxxx‘ and a.col1 is null and a.col2=‘‘ and b.status!=8 
) as v 
 

SQL优化例子

原文:https://www.cnblogs.com/vansky/p/9838016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!