如果组中的至少一行与条件匹配,则排除组

时间:2015-03-20 08:21:14

标签: mysql sql

这是我的样本表:

-----------------------------------
    name    | price |    status   
------------+-------+--------------
 apple      | 50.00 |
 apricot    | 30.00 |
 cherry     | 32.00 |
 orange     | 25.00 |
 pine-apple | 35.00 |
 orange     | 20.00 | out-of-stock
 apricot    | 35.00 | out-of-stock
 grapes     | 30.00 | out-of-stock

我需要检索price小于40的记录,并排除同一name statusout-of-stock至少一次的记录。

所需的结果如下所示:

------------
    name
------------
 cherry      
 pine-apple  

SQLFiddle

2 个答案:

答案 0 :(得分:3)

使用NOT EXISTS来避免售完水果。

select name
from fruits f1
where price < 40.00
and not exists (select * from fruits f2
                where f1.name = f2.name
                  and status = 'out-of-stock')

答案 1 :(得分:1)

您可以使用LEFT JOINIS NULL检查:

SELECT t1.* 
FROM fruits t1 
LEFT JOIN ( SELECT name 
            FROM fruits
            WHERE status = 'out-of-stock') t2 ON t1.name = t2.name
WHERE t1.price < 40
  AND t2.name IS NULL

SQLFiddle

IN

SELECT t1.* 
FROM fruits t1 
WHERE t1.price < 40 
  AND t1.name NOT IN ( SELECT name
                       FROM fruits
                       WHERE status = 'out-of-stock')

SQLFiddle