在子查询中使用And运算符

时间:2014-02-11 17:29:34

标签: mysql sql mysql-workbench

找到保留红色和绿色船的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') ;

这里我需要检查第一和第二子查询的结果中是否存在“bid”,然后选择sid。虽然我不考虑第二个子查询结果的结果。

5 个答案:

答案 0 :(得分: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 :(得分:1)

我会写

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

答案 2 :(得分:1)

你需要在bin中指定两个子查询,就像红色和绿色的船(和船只只能是一种颜色)一样,你实际上是在说你想要红色或绿色的保存者,所以或者在这里是合适的。

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与DISTINCT在大桌子(40GB +)上的效率有不同的经验

更新:由于我错过了解您之前的问题,这可能是一个更合适的解决方案:

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')上的布尔检查的总和,如果你没有任何红色(或绿色)的出价船并且通过那些,则总和将为零在一起,你知道红色的总和&gt; 1和sum(绿色)&gt; 1.

还有一个方便你玩:http://sqlfiddle.com/#!2/b5ec1/8

答案 3 :(得分: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'));

答案 4 :(得分:0)

您也可以考虑这种方法(用连接替换子查询):

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

此查询会返回所有sid个预留条件,其中包含具有相同bid的船只条目且具有指定颜色之一。