Sqlite3
如何选择仅作为宠物而非食物的动物? POF是“宠物或食物”栏目。动物可以属于这两个类群。这是实际问题的较小版本。我不想将其拆分为更多表。
animal pof
----------
fish pet
fish food
pig food
cat pet
dog pet
horse pet
mouse pet
duck pet
duck food
cow food
rabbit pet
rabbit food
gerbil pet
worm <null>
chicken food
我有以下内容,但看起来很尴尬:
SELECT * from
(SELECT NAME, POF, count(*) as cnt
FROM ANIMALS
GROUP BY NAME) AS GC
WHERE GC.cnt == 1 AND GC.POF == 'pet'
正确产生:
NAME POF cnt
---------------
cat pet 1
dog pet 1
gerbil pet 1
horse pet 1
mouse pet 1
最佳答案
使用NOT IN
排除所有具有pof = 'food'
的动物:
select *
from animals
where pof = 'pet'
and animal not in (select animal from animals where pof = 'food')
或者,如果您只想要animal
列,您可以使用EXCEPT
:
select animal from animals where pof = 'pet'
except
select animal from animals where pof = 'food'
请参阅demo .
关于sql - 如何选择属于一个组而不是另一个组的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63495686/