返回介绍

solution / 1300-1399 / 1350.Students With Invalid Departments / README_EN

发布于 2024-06-17 01:03:20 字数 3476 浏览 0 评论 0 收藏 0

1350. Students With Invalid Departments

中文文档

Description

Table: Departments

+---------------+---------+
| Column Name   | Type  |
+---------------+---------+
| id      | int   |
| name      | varchar |
+---------------+---------+
In SQL, id is the primary key of this table.
The table has information about the id of each department of a university.

 

Table: Students

+---------------+---------+
| Column Name   | Type  |
+---------------+---------+
| id      | int   |
| name      | varchar |
| department_id | int   |
+---------------+---------+
In SQL, id is the primary key of this table.
The table has information about the id of each student at a university and the id of the department he/she studies at.

 

Find the id and the name of all students who are enrolled in departments that no longer exist.

Return the result table in any order.

The result format is in the following example.

 

Example 1:

Input: 
Departments table:
+------+--------------------------+
| id   | name           |
+------+--------------------------+
| 1  | Electrical Engineering   |
| 7  | Computer Engineering   |
| 13   | Bussiness Administration |
+------+--------------------------+
Students table:
+------+----------+---------------+
| 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       |
+------+----------+---------------+
Output: 
+------+----------+
| id   | name   |
+------+----------+
| 2  | John   |
| 7  | Daiana   |
| 4  | Jasmine  |
| 3  | Steve  |
+------+----------+
Explanation: 
John, Daiana, Steve, and Jasmine are enrolled in departments 14, 33, 74, and 77 respectively. department 14, 33, 74, and 77 do not exist in the Departments table.

Solutions

Solution 1: Subquery

We can directly use a subquery to find all students who are not in the Departments table.

# Write your MySQL query statement below
SELECT id, name
FROM Students
WHERE department_id NOT IN (SELECT id FROM Departments);

Solution 2: Left Join

We can also use a left join to join the Students table with the Departments table on the condition of Students.department_id = Departments.id, and then filter out the students whose Departments.id is NULL.

# Write your MySQL query statement below
SELECT s.id, s.name
FROM
  Students AS s
  LEFT JOIN Departments AS d ON s.department_id = d.id
WHERE d.id IS NULL;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文