2012-10-09 15 views
1

我有關於如何執行SQL查詢的問題。我寫了一個我在這裏使用的示例數據庫,我試圖讓所有想要幫助的人保持簡單。SQL根據不同的表關係找到最經常性的元素

Officer    Permit    Vehicle    Dispatch 

Oid | Dname | Rank Oid | Type | Model Vid | Type | Model Did | Oid | Location 
------------------ ------------------ ------------------ -------------- 
1 | John | Jr 1  D1  Ford 1  D1  Ford 1  1  Hill 
2 | Jack | Sr 1  D2  Ford 2  D2  Ford 2  2  Beach 
3 | Jay | Jr 2  D1  Ford 3  D3  Ford 3  3  Post 
4 | Jim | Jr 3  D1  Ford 4  D4  Ford 4  1  Beach 
5 | Jules | Sr 5  D1  Ford 5  D5  Ford 5  2  Hill 
        1  D3  Ford       6  4  Post 
        2  D2  Ford       7  5  Hill 
        4  D1  Ford       8  5  Beach 
        1  D5  Ford       9  2  Post 

表之間的關係是:

Officer - lists the officer by OID(officer ID)/Name/Rank where Sr is highest, Jr is lowest. 
Permit - Officers are required to have a permit depending on the vehicle they will be using, Oid for Officer ID, Type for the vehicle and Model. 
Vehicle - Vid for vehicle ID, Type and Model 
Dispatch - Did for Dispatch ID, keeps track of which officer (Oid) was dispatched to which location (Location) 

問:我需要知道兩件事情從這裏開始。 首先是我怎麼知道哪個軍官被允許駕駛所有車型? 二是如何知道哪個官員已派往所有派遣的地點?

編寫這兩個查詢對我來說是一場噩夢,我嘗試過加入不同的表格,但是我仍然無法從其中獲得最經常性的元素(我不知道該怎麼做!),任何幫助都將不勝感激!

回答

2

第一個問題:

select Oid, count(*) type_count 
from Permit 
group by Oid 
having type_count = (select count(distinct Type, Model) from Vehicle) 

二:

select Oid, count(*) location_count 
from Dispatch 
group by Oid 
having location_count = (select count(distinct Location) from Dispatch) 

看到一個模式?

+0

我確實看到它,非常好我將盡快測試它。順便說一句,您使用關鍵字'有',這使事情變得更簡單。但是,有沒有辦法做到這一點,而不使用它? – AGE

+1

'SELECT ... HAVING '主要相當於SELECT * from(SELECT ...)WHERE '。 – Barmar

相關問題