MySQL子查询优化-子语句含有group by时

来源:互联网 发布:上海曼威网络 编辑:程序博客网 时间:2024/04/29 17:59

当我使用Mysql进行下列语句的查询时:
select count(1) from jy_info_user 
where user_card != '' 
and id IN (select id from jy_erp.jy_info_user where ifnull(user_card,'')!='' group by user_card HAVING count(1)=1 )



很简单的一个统计数量,却用了一分多钟。
我的数据有3万多条,这样查下来,每次查询太慢。于是去百度了一下。


下面是网上查询比较多的关于MYsql子查询优化的文章:
http://www.cnblogs.com/xh831213/archive/2012/05/09/2491272.html


里面只是说到了子查询,很明显,我的子查询中有group by,遇到这种情况,一般想到的是,不适用


于我这种子查询。


有没有优化的方案呢?


于是我将子查询语句包装成一个独立的表,再进行查询:
select count(1) from jy_info_user 
where user_card != '' 
and id IN ( select id from (select id from jy_erp.jy_info_user   where ifnull(user_card,'')!='' group by user_card HAVING count(1)=1 )  as users )


其实这样没有任何作用,依旧很慢。


想到在join上面下工夫,因为上面的文章中,提到join是最快的方式:


于是写出了这样的语句:
select count(1) 
from jy_info_user a
join (select id from jy_erp.jy_info_user where ifnull(user_card,'')!='' group by user_card HAVING count(1)=1 ) as b on a.id=b.id
where a.user_card != '' 



查询出结果:0.17s,比之前快太多了,基本上能够接受。


可以看出,查询语句使用了上面两种方式:
1. 将需要group by 的语句 作为一个表进行包装,得到新的表数据。
2. join 可以将两个表进行级联查询,从而避免了多对多的数据关系。


因为join本身包含了筛选的功能,所以查到的结果,都跟子语句的数据有关联。


这样就大功告成了!
0 0