【问题标题】:Selecting tuples from a multivalue attribute从多值属性中选择元组
【发布时间】:2015-04-10 21:26:12
【问题描述】:

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

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 在所有相同团队中的人。我尝试过 group by 并设置子句,但是当我按人分组时,除第一个以外的任何团队都会丢失,所以我有点卡住了。

感谢任何帮助。

【问题讨论】:

    标签: sql sqlite multivalue


    【解决方案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 相同的团队数量,这意味着他们一直在相同的团队中。

    【讨论】:

    • 太好了,我最终使用 count(*) 来比较这两个表,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-09-01
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    相关资源
    最近更新 更多