下面是两个表的图片,所有者和车辆。
我需要找到拥有所有类型自行车的车主。
例子:
O_id 100、O_id 101、O_id 102 有 V_id=1 的自行车,但是
O_id 103 有所有类型的自行车(V_id = 1 and V_id = 5)
如何编写查询来获取这些详细信息?
我的查询:
select o.o_id from owner o,vehicles v where
o.v_id = v.v_id where v_type = 'bike'
这显示所有拥有自行车的车主,但不显示拥有所有自行车的车主
最佳答案
按你想得到的o_id
分组。
仅取那些具有相同数量 (count(v_id)
) 的自行车的组 (select count(*) from vehicles where v_type = 'bike')
select o.o_id
from owner o
join vehicles v on o.v_id = v.v_id
where v.v_type = 'bike'
group by o.o_id
having count(distinct v.v_id) = (select count(*) from vehicles where v_type = 'bike')
关于sql - 选择拥有所有类型自行车的所有者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32847238/