2015-09-29 343 views
1

下面是兩張表,車主和車輛的圖片。 我需要找出擁有各種類型自行車的車主。
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' 

這正顯示出誰擁有自行車全體業主,但業主沒有誰擁有所有自行車

回答

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') 
+0

可以在使用子查詢進行老實說? ,我覺得這有點難以理解 – Pradeep

+0

這是使用子查詢。我對答案添加了解釋 –

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'); 
-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

+0

如果沒有一個車主擁有所有的自行車,該怎麼辦? –

+0

如果詢問您的問題是讓車主擁有所有的自行車,那麼如果沒有車主擁有所有(1個或更多)自行車,則回答爲無。對?或者我失去了一些東西。 –

+0

沒錯。但是,你的查詢沒有返回什麼呢?我不這麼認爲。或者我錯過了什麼? –