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 a
WHERE hobby = 'basketball'
AND EXISTS (SELECT * from TEST b
WHERE a.nameb.name AND b.hobby = 'badminton');
但是有重复的情况如何处理?
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 b
WHERE a.hobby = 'basketball'
AND a.name = b.name
--EOF--

posted @ 2012-08-27 15:27  xxd  阅读(1224)  评论(0编辑  收藏  举报