给出两个表
PilotGroup表
Pilot Plane
Jon Smith A1-Fighter
Jon Smith B1-Fighter
Gravell A2-Fighter
Jon Skeet A1-Fighter
Jon Skeet B1-Fighter
Jon Skeet A4-Fighter
Gravell A5-Fighter
SouthOperation表
Plane
A1-Fighter
B1-Fighter
任务是打印经过A1-Fighter和B1-Fighter训练的飞行员名字。
我通过执行
得到了结果select distinct pilot from PilotGroup as pg1
where not exists
(
select * from SouthOperation Sop where
not exists
(
select *from PilotGroup as pg2 where ( pg1.pilot = pg2.pilot)
and
(pg2.plane= Sop.plane)
)
)
是否有其他方法可以针对其他表搜索行?
答案 0 :(得分:3)
select
pilot
from
pilotgroup pg
inner join
southoperation sop on (pg.plane = sop.plane)
group by
pilot
having
count(pg.plane) = (select count(*) from southoperation)
答案 1 :(得分:2)
SELECT Pilot FROM PilotGroup
INNER JOIN SouthOperation ON PilotGroup.Plane = SouthOperation.Plane
GROUP BY Pilot
HAVING COUNT(SouthOperation.Plane) = 2
答案 2 :(得分:2)
任务是打印经过A1-Fighter和B1-Fighter训练的飞行员名字。
如果您预先拥有这些值,则根本不需要SouthOperation
:
SELECT Pilot FROM PilotGroup WHERE Plane = 'A1-Fighter'
INTERSECT
SELECT Pilot FROM PilotGroup WHERE Plane = 'B1-Fighter'
但是,如果您实际上是指“在SouthOperation
中打印所有飞机上受过培训的飞行员的姓名”,我的问题是:SouthOperation
中是否只有两行?或者可能更多?
答案 3 :(得分:2)
你发布的问题几乎完全符合Joe Celko撰写的这篇文章中的例子:Divided We Stand: The SQL of Relational Division,实际上,它涵盖了这样一个事实,即“适当”的术语是关系分割。
答案 4 :(得分:1)
declare @t table (pilot int, plane int);
insert into @t
select * from (select 1 pilot, 1 plane union all
select 1, 2 union all
select 2, 1 union all
select 3, 3 union all
select 4, 1 union all
select 4, 2) t
select t1.pilot
from @t t1, @t t2
where t1.pilot = t2.pilot and t1.plane = 1 and t2.plane = 2
group by t1.pilot