我正在学习使用 PostgreSQL 作为 DBMS 的 SQL,但我遇到了一些看似简单的查询问题。 我应该找到语言或年份与所有其他应用程序不同的应用程序。 App表有3个属性:id(每个app唯一)、year、language
我的解决方案无效(无结果):
select p.id, p.language, p.year
from app p
where not exists (select *
from app p2
where (p.id!=p2.id) AND (p.language=p2.language OR p.year=p2.year))
我的表中有条目:
最佳答案
将此作为两个单独的比较:
select p.id, p.language, p.year
from app p
where not exists (select 1
from app p2
where p.id <> p2.id AND p.year = p2.year
) or
not exists (select 1
from app p2
where p.id <> p2.id AND p.language = p2.language
) ;
将它们组合成一个语句的问题在于,其中一个比较会覆盖另一个。因此,如果另一行存在重复的 language
,则您有一个匹配的行并且 not exists
过滤器生效。甚至不需要查看 year
。
关于SQL exist 子句始终为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47058931/