【问题标题】:Find the sailors that have been on EVERY boat找到每艘船上的水手
【发布时间】:2021-02-27 00:14:28
【问题描述】:

我不知道如何用通用的方式解释这个问题,所以我将发布具体案例:

我有 3 张桌子:

水手们:

S(ids, names, rating, age)

船:

B(idb, nameb, color)

预订:

Bo(ids, idb, date)

我必须编写一个查询来查找所有预订了每艘船的水手。

即使我发布了一个特定案例,我也想要一个通用的答案,可以应用于同类的每个问题。

提前谢谢你。

【问题讨论】:

  • 查找没有船的水手,该水手没有预订记录。

标签: sql group-by count distinct


【解决方案1】:

您可以将sumin 一起使用:

select * from sailors s1 group by ids having (select sum(idb in (select b2.idb from bookings b2 where b2.ids = s1.id)) from boats) = (select count(*) from boats)

【讨论】:

    【解决方案2】:

    您可以通过此查询获取预订每艘船的水手ID:

    select ids
    from bookings
    group by ids
    having count(distinct idb) = (select count(*) from boats)
    

    所以要么和运算符IN一起使用它:

    select * from sailors
    where ids in (
        select ids
        from bookings
        group by ids
        having count(distinct idb) = (select count(*) from boats)
    )
    

    或加入sailors:

    select s.*
    from sailors s 
    inner join (
        select ids
        from bookings
        group by ids
        having count(distinct idb) = (select count(*) from boats)
    ) t on t.ids = s.ids
    

    【讨论】:

    • 这在测试数据上应该工作得很好,但在实际数据上应该比not exists慢得多。
    • GSerg 你能说得更具体点吗?
    • @GSerg 你能发布一个不存在的解决方案吗?
    • @GuglielmoLaMastra stackoverflow.com/a/35212957/11683stackoverflow.com/q/5264658/11683,还有很多其他人。
    • @GSerg 我的意思是适用于这个要求的解决方案。
    猜你喜欢
    • 2017-01-09
    • 2017-09-29
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多