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
- MySQL子查询优化-子语句含有group by时
- 标量子查询优化(用group by 代替distinct)
- group by 字段 count 中包含子查询 优化 方式
- mysql group by 查询语句
- mysql子查询优化
- mysql 子查询优化
- mysql常用查询:group by,左连接,子查询,having where
- Mysql group by语句的优化
- Mysql group by语句的优化
- Sql Server子查询、GROUP BY分组、having查询
- Sql Server子查询、GROUP BY分组、having查询
- Mysql子查询优化技术
- 优化mysql标量子查询
- MySQL子查询效率优化
- MySQL子查询的优化
- Mysql 子查询效率优化
- mysql in() 子查询 优化
- 优化Group By语句
- LeetCode之Binary Tree Maximum Path Sum
- nyoj 1242 Interference Signal (河南省第八届acm程序设计大赛)
- 初来乍到
- 【每周一文】Supervised Sequence Labelling with Recurrent Neural Networks
- 过桥问题 其实很水 就是很水
- MySQL子查询优化-子语句含有group by时
- HDOJ 1028 数的拆分 (母函数)
- 【NYOJ】[57]6174问题
- 97. Sort Colors
- struts2中的动态方法调用DMI
- 可视化PK纯代码
- 【设计模式】—-(2)工厂方法模式(创建型)
- [LeetCode] 105 & 106
- 多线程