只在哪里查询?

时间:2014-11-06 03:28:09

标签: sql sqlite

sqlite中是否有像'only'这样的关键字?我必须写一个查询来显示只保留红船的水手名字。所以我目前的查询是:

select s.sname
from sailor s, boat b, reservation r
where s.sname = r.sname
and b.bname = r.bname
and b.color = 'red';

上面的查询问题是它还显示了保留红色+其他颜色船的水手名称。我的查询结果:

a reserve red boat
a reserve green boat
b reserve red boat

但它应该只显示b,因为他只保留红船。

2 个答案:

答案 0 :(得分:1)

您可以使用NOT EXISTS子句仅使用red船来过滤水手。

select r.sname
from reservation r
join boat b
on b.bname = r.bname
and b.color = 'red'
and not exists ( select 1 from reservation r2
                 join boat b2
                 on r2.bname = b2.bname
                 and r2.sname = r.sname
                 and b2.color <> 'red' )

答案 1 :(得分:0)

目前有多种选择。您可以使用{/ 1}}运算符,例如

NOT IN

此外,并非每个水手都会预订船只。因此,在这种情况下,您最好选择select s.sname from sailor s, boat b, reservation r where s.sname = r.sname and b.bname = r.bname and b.color NOT IN (select distinct color from boat where color <> 'red'); 而不是LEFT JOIN。另外,我认为你的意思是做一个INNER JOIN水手名字,如下所示

group by