选择拥有所有类型自行车的车主

时间:2015-09-29 14:53:35

标签: sql database postgresql join subquery

下面是两张桌子,车主和车辆的图片。 我需要找出拥有所有类型自行车的车主 enter image description here 例: O_id 100,O_id 101,O_id 102有自行车,V_id = 1,但是
O_id 103具有所有类型的自行车(V_id = 1和V_id = 5)
如何编写查询以获取这些详细信息? 我的查询:

select o.o_id from owner o,vehicles v where
o.v_id = v.v_id where v_type = 'bike'

这显示了所有拥有自行车的车主,而不是拥有所有自行车的车主

3 个答案:

答案 0 :(得分:2)

按照您要获得的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')

答案 1 :(得分:0)

with bykes as (
    select array_agg(v_id) as byke_ids
    from vehicle
    where lower(v_type) = 'byke'
), owner as (
    select o_id, array_agg(v_id) as v_ids
    from owner
    group by o_id
)
select o_id
from owner cross join bykes
where v_ids @> byke_ids
;
o_id 
------
103

架构:

create table owner (
    o_id int,
    v_id int
);
create table vehicle (
    v_id int,
    v_type text
);
insert into owner (o_id, v_id) values
(100, 1),
(101, 1),
(102, 1),
(103, 1),
(100, 2),
(101, 3),
(103, 5);

insert into vehicle (v_id, v_type) values
(1, 'Byke'),
(2, 'Car'),
(3, 'Car'),
(4, 'Car'),
(5, 'byke');

答案 2 :(得分:-1)

以下是使用子查询和连接查询的两个查询:

模式:

drop table vehicle;
drop table owner;
create table vehicle(V_id int, V_type varchar(20));
create table owner(O_id int , V_id int);
insert into vehicle values(1,'Bike');
insert into vehicle values(2,'Car');
insert into vehicle values(3,'Car');
insert into vehicle values(4,'Car');
insert into vehicle values(5,'bike');
insert into owner values(100, 1);
insert into owner values(101, 1);
insert into owner values(102, 1);
insert into owner values(103, 1);
insert into owner values(100, 2);
insert into owner values(101, 3);
insert into owner values(103, 5);

子查询:

postgres=# select count(*) as bike_count, O_id  from owner where V_id in (
postgres(#    select V_id from vehicle where upper(V_type) = 'BIKE'
postgres(# )
postgres-# group by 2
postgres-# order by 1 desc
postgres-# ;
 bike_count | o_id
------------+------
      2 |  103
      1 |  101
      1 |  100
      1 |  102
(4 rows)

加入查询:

postgres=# select count(*) as bike_count, O_id  from owner o join vehicle v using(v_id)
postgres-# where  upper(v.V_type) = 'BIKE'
postgres-# group by 2
postgres-# order by 1 desc
postgres-# ;
 bike_count | o_id
------------+------
      2 |  103
      1 |  100
      1 |  102
      1 |  101
(4 rows)

如果您只想要所有者,则可以将查询限制为1