sql - 找到每艘船上的水手

标签 sql group-by count distinct

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

我有 3 张 table :

水手们:

S(ids, names, rating, age)

船:

B(idb, nameb, color)

预订:

Bo(ids, idb, date)

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

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

提前谢谢您。

最佳答案

您可以通过以下查询获取预订了每艘船的水手的 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)
)

或加入水手:

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

关于sql - 找到每艘船上的水手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64847149/

相关文章:

linux - 在文件中查找部分重复行并计算每行重复了多少次?

mysql - 完整的外部自连接以及两个别名 mysql 的计数

r - 如何在 R 中创建一个计算唯一值的新列

.net - 在 SQL 中正确使用 IN

r - 基于几个不同的(子)分组(列)计算一列中唯一字符元素的数量

sql - 使用派生字段 Postgresql 分组

sql - 数据透视表返回带有 NULL 的多行,结果应分组在一行上

mysql - 具有表值条件的 Laravel 查询

sql - 使用第三个表中的共同 id 重新连接两个 sql 表

PHP MySQL INSERT INTO解析错误