如何通过其ID和标题(来自表格&#39;考试&#39;)选择所有考试,学生(表格&#39;成绩&#39;)尚未撰写?< / p>
表:成绩
+--------------+----+----
|student_number|e_id| ...
+--------------+----+----
|888075 |1 | ...
|888075 |2 | ...
|888075 |4 | ...
|637020 |2 | ...
+--------------+----+----
表:考试
+----+------+
|e_id|title |
+----+------+
|1 |exam 1|
|2 |exam 2|
|3 |exam 3|
|4 |exam 4|
+----+------+
在这种特殊情况下,我希望学生888075
得到以下输出:
+--+------+
|id|title |
+--+------+
|3 |exam 3|
+--+------+
我只需要反向选择:
SELECT e.e_id as id, e.title as title
FROM grades g
LEFT JOIN exams e
ON g.e_id = e.e_id
WHERE g.student_number = '888075'
答案 0 :(得分:2)
您的查询已关闭 - 只需反转联接并相应地检查null
:
SELECT e.e_id as id, e.title as title
FROM exams e
LEFT JOIN grades g ON g.e_id = e.e_id
AND g.student_number = '888075'
WHERE g.e_id IS NULL
答案 1 :(得分:0)
您需要选择那些不在e_id
的学生参与的e_id
。
SELECT aa.e_id AS id, aa.title
FROM exams AS aa
WHERE e_id NOT IN (
SELECT e_id
FROM grades
WHERE student_number = '888075'
GROUP BY e_id
);
OR
SELECT aa.e_id AS id, aa.title
FROM exams AS aa
WHERE e_id NOT IN (
SELECT DISTINCT e_id
FROM grades
WHERE student_number = '888075'
);
OR
SELECT aa.e_id AS id, aa.title
FROM exams AS aa
WHERE NOT EXISTS (
SELECT e_id
FROM grades AS bb
WHERE aa.e_id = bb.e_id AND bb.student_number = '888075'
);