2014-11-06 162 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