【问题标题】:Usage of exists and not exists in SQLSQL中exists和not exists的用法
【发布时间】:2021-08-29 11:15:09
【问题描述】:

SQL 代码 sn-p #1:

select *  
from customer 
where exists (select null) 
order by residence desc; 

SQL 代码 sn-p #2:

select customer_id, customer_name  
from customer
where exists (select customer_id 
              from customer 
              where residence = 'los angeles'
                and age > 20 and age < 40);

enter image description here

enter image description here

这两个查询都返回表中的所有行。我不明白其中的区别。谁能解释一下这是为什么?

还请简要说明existsnot exists 的作用。

谢谢

【问题讨论】:

  • > 上述两个查询都返回记录中的所有行。 ... ?请提供示例和数据样本。
  • 我附上了这两个查询的结果集。请通过它,看看你是否可以帮助我。谢谢

标签: sql postgresql exists pgadmin-4 not-exists


【解决方案1】:

如果子查询至少返回一行,则 EXISTS 的结果为真。如果子查询没有返回任何行,则 EXISTS 的结果为 false。

https://www.postgresqltutorial.com/postgresql-exists/

两个序列都返回至少 1 行,并且主查询上没有过滤器,因此两个主查询都返回所有行

  • 选择 null -> 1 行

  • 选择 customer_id 来自客户 居住地='洛杉矶' 并且年龄 > 20 并且年龄 一些行

如果要选择子集,只需在主查询中使用 where,无需使用退出。

【讨论】:

  • 所以如果exists为真,使用exists不会过滤记录?!!谢谢
  • 正确,哪里就够了(如果你使用组的话)。
  • 错误:列“purchase_rate”不能自动转换为整数 提示:您可能需要指定“USING purchase_rate::integer”。我试图改变数据类型。但是出现了这个错误请解释如何解决这个问题
  • 不要混淆你的问题,打开一个新帖子会很困难。
  • @Dri372 。 . .作为附加说明:我强烈建议不要将SELECT NULLEXISTS 一起使用,正是因为“NULL”与“No rows”的混淆。另外,SELECT 1 更容易输入。
猜你喜欢
  • 2011-05-26
  • 2015-02-17
  • 2010-11-13
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 2013-02-10
  • 2021-03-02
  • 2013-04-17
相关资源
最近更新 更多