从多值属性中选择元组

Selecting tuples from a multivalue attribute

我正在尝试获取以下示例的查询,其中我需要 select 与某个人一起为同一支球队(或同一支球队和其他球队)效力过的所有人。例如

person  teamName
1       maple leafs
1       rangers
2       red wings
3       rangers
3       avalanche
3       maple leafs

我正在尝试创建一个显示 "find all players who have played on the same teams as player 1" 的查询。在上面的示例中,它应该 return 玩家 1 和 3。我有一些工作,即

select person from teams where teamName = 'maple leafs' intersect select person from teams where teamName = 'rangers';

但是编码太硬(玩家可能会被派往另一支球队)。我可以通过以下

获得一份球员名单
create table temp as select teamName from teams where person = 1;
select * from temp join teams on temp.teamName = teams.teamName;

但我不知道如何提取与玩家 1 在同一团队中的人。我已经尝试过 group by 和 having 子句,但是当我按人分组时,任何团队都比第一个多迷路了,所以我有点卡住了。

感谢任何帮助。

您可以像这样概括查询:

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);

第一个子select 将团队限制为只有 1 号成员所在的团队。但这仍然包括至少参加过其中一支球队但不是全部球队的人。然后 HAVING 子句确保查询返回的人拥有与人 1 相同的团队数量,这意味着他们一直在所有相同的团队中。