我想做一个关系除法查询。首先,这是每个表的结构:
学生
id
name
课程
id
name
Student_passed_course (存储通过哪个课程的联结表)
id_student
id_course
基本上,我想要的是使用Course
(或JOIN
等)获取已通过表LEFT JOIN
中所有课程的学生的姓名。我已经使用NOT EXISTS
实现了解决方案。
答案 0 :(得分:0)
基于JOIN的解决方案如下:
SELECT s.name AS student_name, c.name as course_name FROM (
SELECT s_id, c_id, SUM(c_exists) AS c_exists, SUM(c_taken) as c_taken, SUM(c_exists)-SUM(c_taken) as not_taken FROM (
SELECT s.id as s_id, c.id as c_id, 1 as c_taken, 0 as c_exists FROM student s JOIN student_passed_course spc ON spc.id_student = s.id JOIN course c ON c.id = spc.id_course
UNION ALL
SELECT s.id as s_id, c.id as c_id, 0 as c_taken, 1 as c_exists FROM student s JOIN course c
) X group BY s_id, c_id) Y
JOIN student s ON s.id = s_id JOIN course c ON c_id = c.id
WHERE not_taken = 1;
我不知道这会比你的解决方案更有效还是更低效。