LeetCode-1350. Invalid Education Students (simple)

Departments table: Departments

+ --------- + --------------- +
| Column the Name | Type |
+ --------------- + + ---------
| the above mentioned id | int |
| name | VARCHAR |
+ --------------- + --------- +
the above mentioned id is the primary key
of the table contains information for each of a university department's id
 

Student Table: Students

+ --------- + --------------- +
| Column the Name | Type |
+ --------------- + + ---------
| the above mentioned id | int |
| name | VARCHAR |
| department_id | int |
+ --------------- + -------- - +
id is the primary key for the table
this table contains the id of each student and his / her attending a university faculty information
 

Write a SQL statement to query those departments where there is no student id and name

Results can be returned in any order

The following is an example of the format return result

Departments 表:
+------+--------------------------+
| id   | name                     |
+------+--------------------------+
| 1    | Electrical Engineering   |
| 7    | Computer Engineering     |
| 13   | Bussiness Administration |
+------+--------------------------+

Students 表:
+------+----------+---------------+
| id   | name     | department_id |
+------+----------+---------------+
| 23   | Alice    | 1             |
| 1    | Bob      | 7             |
| 5    | Jennifer | 13            |
| 2    | John     | 14            |
| 4    | Jasmine  | 77            |
| 3    | Steve    | 74            |
| 6    | Luis     | 1             |
| 8    | Jonathan | 7             |
| 7    | Daiana   | 33            |
| 11   | Madelynn | 1             |
+------+----------+---------------+

Results Table:
+ ------ + ---------- +
| the above mentioned id | name |
+ ------ + ---------- +
| 2 | John |
| 7 | Daiana |
| 4 | Jasmine |
| 3 | Steve |
+ ------ + ---------- +

Department John, Daiana, Steve and Jasmine are located 14, 33, 74 and 77, 14, 33, 74 and 77 do not exist in the department table

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/students-with-invalid-departments
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Moderation: Write a SQL statement to query those departments where there is no student id and name

Thoughts: The query does not exist faculty students directly through exclude the presence of the rest is non-existent.

Problem solving:

method one:

SELECT Students.id, Students.name 
FROM Students LEFT JOIN Departments ON Students.department_id = Departments.id 
WHERE ISNULL(Departments.id);

Method Two:

SELECT id, name
FROM Students
WHERE NOT department_id IN (
    SELECT id 
    FROM Departments
    );

 Knowledge points:

Published 144 original articles · won praise 2 · Views 5728

Guess you like

Origin blog.csdn.net/Hello_JavaScript/article/details/104792815