A little understanding of SQL subquery NOT EXISTS

A little understanding of SQL subquery NOT EXISTS

  First, understand the usage of NOT EXISTS in subqueries

SELECT--1号SELECT
FROM table 
WHERE NOT EXISTS (
SELECT--2号SELECT
FROM table
WHERE)

  To make the WHERE in the SELECT query No. 1 true, the result of the SELECT query No. 2 needs to be empty.
  Let's look at an example.

Student table

Insert picture description here

Student selection form

Insert picture description here

  • Take the following query statement as an example

Requirement: Inquire about the student ID and name of the students who have taken at least all courses selected by the student whose student ID is "g0940201".

SELECT S.学号, S.学生姓名			--1号SELECT
FROM [学生] S
WHERE NOT EXISTS (
	SELECT *						--2号SELECT
    FROM [学生选课] A
    WHERE A.学号='g0940201' 
    AND NOT EXISTS (
    	SELECT *					--3号SELECT
    	FROM [学生选课] B 
        WHERE S.学号 = B.学号 
        AND B.课程号 = A.课程号
    )
);

  In SELECT No. 3, inquire whether each student B in the selected course of designated student A has also selected. If selected, SELECT No. 3 has the result, the WHERE value in SELECT No. 2 is false, and SELECT No. 2 has no query result. If all courses have been tested and there is no query result for SELECT No. 2, then the WHERE value in SELECT No. 1 is true, and the next student will be tested. If there is a course that student A chooses but student B does not choose, SELECT No. 3 has no result, the WHERE value in SELECT No. 2 is true, SELECT No. 2 has the query result, and the WHERE value in SELECT No. 1 will always be False, until all courses have been tested, the next student will be tested.

state machine

Insert picture description here
  The input queue is all courses selected by student A, and the condition is whether student B chooses this course. If it ends in state 2, save the query result and check the next student, if it ends in state 3, do not save the query result, and directly check the next student.

Guess you like

Origin blog.csdn.net/weixin_43902773/article/details/109883564