An interesting SQL Statement Analysis

Source: Internet
Author: User

An interesting SQL Statement Analysis

This statement has plagued me for a long time. It was rarely used in the past due to busy work and work, even if you encounter this requirement, you can use another statement instead or implement it in another solution, so you have no time to ignore it. This Sunday, I had nothing to worry about. I thought carefully and analyzed this statement.

Student table S (SNO int PK, Sn varchar (8) -- SnO indicates the student ID and Sn indicates the Student name.
Curriculum C (CNO int PK, CN varchar (50) -- CNO indicates the course number, and CN indicates the course name
Optional table SC (SNO int PK, CNO int PK, score number (), FK (SNO, CNO) -- score is the score.

-- The following statement is used to find the names of students who have selected all courses.
Select Sn
From S
Where (not exists
(Select *
From C
Where not exists
(Select *
From SC
Where SnO = S. SnO and CNO = C. CNO )))

The analysis is as follows:
[1]:
Select *
From C
Where (not exists
(Select *
From SC
Where SnO = 10005 and CNO = C. CNO ))
-- Find the courses not selected by students whose student ID is 10005.
[2]:
Select Sn from S
Where (not exists ([1] :))
-- If [1]: when some statements are executed as null records, that is, if the not exists ([1] :) condition is true
-- Students whose student ID is 10005 take all the courses, and so on if [1 ]:
-- SnO = 10005 changed to sno = S. Sno, which indicates that the names of the students who took all the courses are obtained.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.