sql 不存在和子查询

标签 sql exists

假设有一个大学数据库

name     |  state | enrollment
=============================
Stanford | CA     | 15000
-----------------------------
Berkley  | CA     | 36000
-----------------------------
MIT      | MA     | 10000
-----------------------------
Cornell  | NY     | 21000

在不使用 max() 的情况下,我可以使用 exists 运算符和子查询获得注册人数最多的大学

select name from college c1 where not exists ( select * from college c2 where c2.enrollment > c1.enrollment);

返回

 Berkeley
(1 row)

如预期的那样

仍然,我不明白查询是如何工作的。 exists 如果子查询至少返回一条记录,则满足条件。所以,在上面,只有当子查询返回一个空集时,才会满足 not exists。或者我以为..

为了检查这一点,我尝试运行子查询

select c2.name from college c2,college c1 where c2.enrollment > c1.enrollment);

但这会返回

  name   
----------
 Stanford
 Berkeley
 Berkeley
 Berkeley
 Cornell
 Cornell
(6 rows)

我在这里真的很困惑..有人可以澄清第一个查询是如何工作的以及为什么我在这里错了吗?

最佳答案

select name from college c1 where not exists ( select * from college c2 where 
c2.enrollment > c1.enrollment);

上面的查询查找可以找到注册值的记录 > 外部查询的当前行。

假设查询以自上而下的顺序运行

  1. 查看 Stanford enrollment 并检查是否有其他行 招生 > 斯坦福大学招生。子查询将返回 2 记录(康奈尔和伯克利)。所以,这不会是一场比赛。
  2. 查看 Berkley enrollment 并检查是否有任何其他行有 enrollment > Berkley enrollment。子查询将返回 0 条记录。因此 NOT EXISTS 条件将为 Berkley 返回 true。

关于sql 不存在和子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8906468/

相关文章:

sql - 累积过去 12 个月的月度总数

sql - 带有大小写和子查询的 PostgreSQL UPDATE 以从正上方的行中获取值

sql - 如何在SQL Server中优化 View 以提高速度

SQL:如果记录列表存在,返回 "true"?

javascript - 检测对象数组中是否存在属性值

mongodb - 蒙哥 : find items that don't have a certain field

mysql - 对此最好的查询是什么?

sql - 删除SQL Server 2008中所有非系统对象的脚本

mysql - 如何通过部分字符串查找单词

sql - 如何修复 “Only one expression can be specified in the select list when the subquery is not introduced with EXISTS” 错误?