gpt4 book ai didi

sql - 如何选择属于一组但不属于另一组的项目

转载 作者:行者123 更新时间:2023-12-04 09:04:11 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com