2014-11-06 62 views
1

在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,因为他只保留红船。

回答

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') 
+0

谢谢你,但它也显示水手谁选择其他颜色的船。 – 2014-11-06 04:52:39

+0

@something,我试过了,它给出了正确的结果,这里是sql小提琴http://www.sqlfiddle.com/#!7/dbaa2/1 – radar 2014-11-06 05:05:56

0

存在多个选项。您可以使用一个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水手名称像下面这样

select s.sname 
from sailor s, 
left join reservation r on s.sname = r.sname 
left join boat b on b.bname = r.bname 
group by s.sname 
having count(*) <= 1 and b.color = 'red' 
+0

谢谢你,我已经尝试了你的两个查询,但它结果与我的查询一样。 – 2014-11-06 04:52:01