获取表B中表A中不存在的所有记录

时间:2018-04-15 07:44:32

标签: mysql sql join

通过Skype的求职面试得到这个问题。我设法截取了问题的截图。

enter image description here 我想这是正确加入的反面,但我无法弄明白。

3 个答案:

答案 0 :(得分:2)

通过反连接实现此目的的一种简单方法:

SELECT d.*
FROM departments d
LEFT JOIN students s
    ON d.DEPARTMENT_ID = s.DEPARTMENT_ID
WHERE
    s.DEPARTMENT_ID IS NULL;

我们还可以使用EXISTS查询:

SELECT d.*
FROM departments d
WHERE NOT EXISTS (SELECT 1 FROM students s WHERE s.DEPARTMENT_ID = d.DEPARTMENT_ID);

答案 1 :(得分:0)

您可以使用子查询来完成此操作。以下是MySQL查询的两个示例。你可以试试这个。

SELECT * 
FROM DEPARTMENT 
WHERE 
DEPERTMENT_ID NOT IN (
   SELECT DEPERTMENT_ID 
   FROM STUDENTS 
   GROUP BY DEPERTMENT_ID) 

使用不存在的另一种方式:

   SELECT d.*
    FROM departments d
    WHERE NOT EXISTS (
         SELECT 1 FROM students s WHERE s.DEPARTMENT_ID = d.DEPARTMENT_ID
    );

答案 2 :(得分:0)

试试这个:

SELECT *
FROM department_table D
WHERE 
NOT EXISTS (SELECT NULL
            FROM student_table B
            WHERE A.department_id=B.department_id);