这是我的样本表:
-----------------------------------
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
status
值out-of-stock
至少一次的记录。
所需的结果如下所示:
------------
name
------------
cherry
pine-apple
答案 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 JOIN
和IS 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
或IN
SELECT t1.*
FROM fruits t1
WHERE t1.price < 40
AND t1.name NOT IN ( SELECT name
FROM fruits
WHERE status = 'out-of-stock')