从多值属性中选择元组
问题描述:
我正在试图获得以下示例的查询,我需要选择所有为某个人玩过相同团队(或同一人)的人。例如从多值属性中选择元组
person teamName
1 maple leafs
1 rangers
2 red wings
3 rangers
3 avalanche
3 maple leafs
我试图创建一个查询,说“查找所有玩家在与玩家1相同的球队上玩过”。在上面的例子中,它应该返回播放器1和3。我已经得到的东西的工作,即
select person from teams where teamName = 'maple leafs' intersect select person from teams where teamName = 'rangers';
但是它太硬编码(球员可能会被发送到另一支球队)。我能得到的球员谁一直在1队的队员有以下
create table temp as select teamName from teams where person = 1;
select * from temp join teams on temp.teamName = teams.teamName;
列表,但我不那么知道如何提取人谁上都是一样的队作为球员1.我我尝试了分组并且有条款,但是当我按人分组时,比第一组更多的任何球队都输了,所以我有点卡住了。
任何帮助表示赞赏。
答
可以概括这样的查询:
select person
from yourtablename
where teamname in (select teamname from yourtablename where person = 1)
group by person
having count(*) = (select count(*) from yourtablename where person = 1);
第一子选择限制球队只是那些人1已经上。但是,这仍然包括那些至少参加过一支球队但并非全部的球员。然后,HAVING子句确保查询返回的人员的团队数量与人员1的确切数量相同,这意味着他们已经参加了所有相同的团队。
非常好,我已经结束了使用计数(*)比较两个表,谢谢! – errorline1 2015-04-10 19:05:44