SQL子查询分析
在这里看到了一个帖子 http://www.iteye.com/topic/1122917,很简单,凑下热闹,因为Oracle,SQLServer的子查询和Join算法的选择很多,但是MySQL方面就没有那么多的选择了,所以很多子查询的性能都很差,这里分析几个帖子里MySQL的答案。
需求:使用SQL语句查出哪些人即会玩basketball又会玩badminton,找出这样的name-hobby组合
create table test (NAME varchar(20) not null, HOBBY varchar(20) not null);
insert into test values('Adam','basketball');
insert into test values('Bill','basketball');
insert into test values('Bill','football');
insert into test values('Cyper','basketball');
insert into test values('Cyper','badminton');
insert into test values('David','basketball');
insert into test values('David','badminton');
insert into test values('David','table tennis');
一个Groupby的写法
select name,group_concat(hobby),count(*)
from test where HOBBY IN ('basketball','badminton')
group by name having count(*)]]]]>1;
一个exists的写法
select * from test aWHERE hobby = 'basketball'AND EXISTS (SELECT * from TEST b
但是有重复的情况如何处理?
insert into test values('Bill','basketball');
insert into test values('Bill','basketball');
insert into test values('David','badminton');
insert into test values('David','badminton');
Groupby的写法需要进化使用distinct
select name,group_concat(distinct(hobby)), count(distinct(hobby))from test where hobby in ('basketball','badminton') group by name having count(distinct(hobby))>1
exists的写法的写法不用修改,但是执行计划是DEPENDENT SUBQUERY,这样效率很差,那么要优化成Derived Table写法,如下
select distinct(a.name) as name,concat(a.hobby, b.hobby) from test a,(SELECT distinct(name) as name , hobby from TEST WHERE hobby = 'badminton') as bWHERE a.hobby = 'basketball'AND a.name = b.name
--EOF--
作者:Buro#79xxd
出处:http://www.cnblogs.com/buro79xxd/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。