相关子查询:EXISTS
内外层两个表之间一定要有某个字段关联起来。
EXISTS
取元组为真(true)
的记录,NOT EXISTS
取元组为假(false)
的记录。
1、 NOT EXISTS
子查询和主查询为不同的两个表
关联关系:student_no=t_student.student_no
SELECT student_name
FROM t_student
WHERE NOT EXISTS
(SELECT *
FROM t_course
WHERE student_no=t_student.student_no AND course_no='007'
);
2、 NOT EXISTS
子查询和主查询为同一个表
取别名自身关联:t1.id=t2.id
SELECT
t1.case_id,
t1.case_type,
t1.is_deleted
FROM `t_case` t1
WHERE NOT EXISTS
(
SELECT * FROM `t_case` t2 WHERE t1.case_id=t2.case_id AND is_deleted=0
);
相关子查询:子查询的查询条件依赖于外层父查询的某个属性值(student_no 和 case_id),因此是相关子查询。
EXISTS
查询的结果会自动去重
https://www.runoob.com/sql/sql-exists.html