SQL根据不同的表关系找到最常见的元素

时间:2012-10-09 19:29:44

标签: mysql 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)

问题:我需要从这里了解一些事情。 首先是我如何知道允许哪些人员驾驶所有类型的车辆? 其次是我如何知道哪些官员被派遣到所有派遣地点?

写这两个查询对我来说一直是个噩梦,我试图加入不同的表格,但我仍然无法从中获得最重复的元素(我不知道如何!)任何帮助将不胜感激!

1 个答案:

答案 0 :(得分: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)

看模式?