我有一个名为food
的示例表item id date
apple 1 in-date
apple 1 in-date
banana 2 rotten
banana 2 in-date
lemon 3 in-date
lemon 3 in-date
我想编写一个只返回所有内容日期的项目的查询 即应归还苹果和柠檬。
我有,
select item
from food
where date = 'in-date';
然而,即使有些已经过时,这也会返回banana
。
任何帮助将不胜感激
答案 0 :(得分:7)
select distinct item
from food
where item not in (select item from food where date<>'in-date')
或者,如果您的SQL支持exists
select distinct item
from food
where not exists (select item from food f where date<>'in-date' and f.item=food.item )
答案 1 :(得分:2)
SELECT item, SUM( CASE mydate WHEN 'in_date' THEN 0 ELSE 1 END ) as rotten
FROM food
GROUP BY item
HAVING rotten==0
答案 2 :(得分:1)
尝试这样的事情: -
select distinct item
from food
where not exists (select item from food f where date<>'in-date' and f.item=food.item )