Sailor (SID, Sname, Age)
Boat (BID, Bname, Color)
Reserve (SID, BID, Day) ------使用此模式,如何才能
查找所有只预订了绿船的水手姓名
我只能设法让所有预定了绿色小船的水手
任何帮助都将不胜感激
发布于 2017-05-15 18:03:19
在这个查询中,我选择了除'green‘以外的所有已预订船只的水手。他们可能也采用了绿色,但是他们的SID将在' in‘查询中被捕获。Outer query (Outer)将通过“where”子句中的“not in”语句排除并提供仅预订了绿船的水手。
您也可以使用left join来做同样的事情,而不是使用'not in‘子句,但我更喜欢使用'not in’而不是'left join‘,因为这将比'left join’效率高得多,特别是在大表的情况下
试试这个:-
Select a.SID,a.Sname,a.Age
from
Sailor a
inner join
Reserve b
on a.SID=b.SID
inner join
Boat c
on b.BID=c.BID
where c.Color='green'
and a.SID not in
(
Select a.SID
from
Sailor a
inner join
Reserve b
on a.SID=b.SID
inner join
Boat c
on b.BID=c.BID
where c.Color <> 'green'
) ;希望这能有所帮助!
发布于 2017-05-15 18:33:27
另一种方式:
select Sailor.* from Boat
inner join
(
select Reserve.sid, Reserve.bid from Reserve
inner join (select SID from Reserve group by SID having count(distinct BID) = 1) t
on Reserve.SID = t.SID
) tt
on Boat.bid = tt.bid
inner join Sailor
on Sailor.sid = tt.sid
where
Boat.color = 'green'好吧,"tt“子查询只包含Reserve表中的那些行(SID和BID),其中SID只有一个惟一的BID。因此,如果SID保留了2个或更多不同的BID,这些行将被忽略。
然后我们将这个连接到Boat表,使用filter where Boat.color = 'green'我们只得到那些船的颜色是绿色的行。
如果在Reserve表中,一个SID具有唯一BID,那么您可以从查询中删除distinct关键字
https://stackoverflow.com/questions/43976488
复制相似问题