SQL exist 子句始终为真

标签 sql postgresql

我正在学习使用 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))

我的表中有条目:

These

最佳答案

将此作为两个单独的比较:

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/

相关文章:

java - MySQL语句中根据另一个表列动态确定列值

sql - SqlServer Compact Edition 中的条件插入

sql - Postgres - 使用 DISTINCT ON 获得第一行,但也获得 COUNT(*) 工作

postgresql - 膝盖 : select rows that are in certain date range

sql - 如何创建一个已经安装了 hstore 扩展的新数据库?

mysql - 如何从一个表中选择 CSV 行并根据键插入到另一个表中?

php - php 中的 sql 运行时不返回任何内容

java - 将 Spring boot JPA(MySQL) 迁移到 JPA(PostgreSQL) 会引发错误

postgresql - Postgres 将 Heroku 从 9.2.4 升级到 9.3

mysql - 为什么 <> ALL 和 NOT IN 在 SQL 中互为别名?