2014-02-11 43 views
1

找到已預留紅色和綠色船的sid。在子查詢中使用和運算符

Table reserves 

sid bid 
22  101 
22  102 
22  103 
31  103 
32  104 

Table Boats 

Bid Color 
101 blue 
102 red 
103 green 
104 red 

是否有可能使用和運營商,子查詢是這樣的

select sid from reserves where bid in 
(select bid from boats where color='red') and 
(select bid from boats where color='green') ; 

在這裏,我需要檢查「投標」是否存在於第一和第二次查詢的結果,然後選擇sid.It雖然不考慮第二個子查詢結果的結果。

回答

1

您需要在bin到指定對陣雙方subsqueries,並作爲你實際上會說紅色和綠色的小船(而小船隻能是一種顏色)你想要紅色或綠色的預留者,所以OR在這裏是合適的。

select sid from reserves where 
bid in (select bid from boats where color='red') 
OR 
bid in (select bid from boats where color='green') ; 

但更有效的方式來做到這一點並不用兩個子查詢,但與聯接:

SELECT sid FROM reserves AS r 
LEFT JOIN Boats as b ON r.bid = b.bid 
WHERE b.color IN ('red', 'green') 

如果你只想要列表包含不可複製的SID,你可以使用如下:

SELECT distinct(sid) FROM reserves AS r 
LEFT JOIN Boats as b ON r.bid = b.bid 
WHERE b.color IN ('red', 'green') 

SELECT sid FROM reserves AS r 
LEFT JOIN Boats as b ON r.bid = b.bid 
WHERE b.color IN ('red', 'green') 
GROUP BY sid 

我曾與GROUP BY的上真正的大表效率VS DISTINCT(40GB +)

UPDATE混經驗:當我想念理解你前面的問題這也許是更合適的解決方案:

SELECT sid FROM reserves AS r 
LEFT JOIN Boats as b ON r.bid = b.bid 
GROUP BY sid 
HAVING sum(b.color = 'red') and sum(b.color= 'green') 

這裏我們正在加入表格,然後按照SID對行進行分組。使用having子句,我們計算b.color ='red'(和'green')上布爾檢查的總和,如果你沒有任何紅色(或綠色)出價船,並且通過這些總和將爲零一起你知道紅色> 1和總和(綠色)> 1。

而一個sqlfiddle讓你玩:http://sqlfiddle.com/#!2/b5ec1/8

+0

不錯,如果船隻包含多次出價,這項工作。我懷疑OP的意思,但因爲我們不知道... – luksch

+0

這不工作:( – Yuvi

+0

然後請重新提出問題,並在更多的細節,所以我們可以瞭解您的數據。 – ModulusJoe

1

嘗試像這樣

SELECT sid 
FROM reserves 
WHERE bid IN 
(select bid FROM boats WHERE color IN ('red','green')) 

(OR)

SELECT sid 
FROM reserves 
WHERE bid IN 
(select bid FROM boats WHERE color = 'red' OR color = 'green') 
1

我會寫

select sid from reserves where bid in 
(select bid from boats where color='red' OR color='green'); 
+0

這個問題就像相同的SID應該有紅色和綠色的顏色,使用或操作使得它喜歡的顏色可以是綠色或紅色。 – Yuvi

0

您也可以考慮這種方式(用加入替換子查詢):

SELECT sid 
FROM reserves 
JOIN boats ON 
reserves.bid = boats.bid 
AND boats.color IN ('red', 'green') 

該查詢返回所有sid儲備有一與指定顏色之一相同的bid進入船隻。

1

它適用於這樣的事情

select sid from reserves where bid in(select bid from boats where color='red') 
and sid in 
(select sid from reserves where bid in(select bid from boats where color='green'));