版本 更新内容 时间 操作人
V1 exists 的使用方法 2020-8-18 呆呆

exists 简介

判断是否存在满足某种条件的记录,如果存在这样的记录就返回真,如果不存在就返回假。

对于 EXISTS来讲:其固定句式为

  1. SELECT <列名> FROM <表1>
  2. WHERE EXISTS (SELECT 1 FROM <表2> where [条件] )

该语句运行时,会遍历 表1的每一行,并判断子查询中的条件是否能被满足(返回真),如果可以满足就留下行,不能就丢弃行,直到结束,返回所有满足条件的行。

浅析MySQL中exists与in的使用 (写的非常好) - struggle_beiJing - 博客园

1、使用exists 替换 in

当我们使用 in (子查询)时,可以考虑用EXSITS代替 in

SQL查询中in和exists的区别分析

-- in
SELECT * from score where s_id not in (SELECT s_id from student)

-- exists
 SELECT * from score 
 where not exists 
             (SELECT 1 from student where score.s_id = student.s_id)

:::info 性能问题:
当表二的行数 > 表 1的行数建议使用 EXISTS ,反之使用 IN
当使用not in 时,都可以使用 not exists 替代。 :::

2、查询表中不存在的数据

语雀内容

3、查询所有行满足某条件

例如查询所有科目分数都在60分以上的学生。
可转化为 没有一门科目的分数小于60

SELECT * from score t1
where not exists (SELECT 1 from score t2 where t1.s_id=t2.s_id and t2.s_score<70)

要理解这个就要知道,在遍历T1的时候,然后T2是对 s_id相连的所有数据进行的判断,里面只有有一个符合条件,就会返回真,然后 not 取否。