假设有下面的数据表:
create table test (
ID` bigint(20) NOT NULL AUTO_INCREMENT,
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');
用SQL语句查出哪些人即会玩basketball又会玩badminton,找出这样的name组合,即输出:
Cyper,David. 我想到了用下面的一些方法:
- 使用最简单的方式,这个里面由于使用了group by,个人感觉不需要加distinct
select name FROM TEST
WHERE hobby in ('basketball','badminton')
group by name having count(name) = 2;
- 使用比较简单的in子查询来实现,需要加distinct
select distinct(name)
from Test
where name in (
select name from Test
where hobby in('basketball','badminton')
group by name
having count(name) = 2
);
- 使用子查询,个人感觉此处不需要加distinct
select from Test a
WHERE hobby = 'basketball'
AND EXISTS (SELECT * from TEST_test b
WHERE a.name = b.name AND b.hobby = 'badminton');
- 使用复杂的子查询,但是效率不敢恭维
select distinct(name) from Test as t1
where exists (
select 1 from Test as t2
where t2.name = t1.name and hobby = 'basketball')
and exists (
select 1 from Test as t3
where t3.name = t1.name and hobby = 'badminton'
);
- 使用表联合查询
select distinct(t1.name)
from Test t1,Test t2,Test t3
where t1.name = t2.name and t1.name = t3.name and
t2.hobby = 'basketball' and t3.hobby = 'badminton';
- 根据题目的要求进行枚举分析
select t1.* from Test t1, Test t2 where t1.name=t2.name
and(
t1.hobby='basketball' and t2.hobby='badminton' or
t2.hobby='basketball' and t1.hobby='badminton'
)