1

我有一个关于如何进行 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)

问:我需要从这里知道一些事情。首先是我如何知道允许哪个警官驾驶所有类型的车辆?二是我怎么知道哪个官员被派到所有派出地点?

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

4

1 回答 1

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)

看到图案了吗?

于 2012-10-09T19:45:52.160 回答