mysql SQL如何根据表2中的用户ID从表1中返回表2中不包括的记录ID

hyrbngr7  于 12个月前  发布在  Mysql
关注(0)|答案(2)|浏览(210)

我有两个表,一个有课程名称和课程ID。第二个表包含学生的ID和他们所选的课程ID。我需要找到所有学生没上过的课的班级号。例如,在表2中,学生03已经选了表1中的01和02班,但没有选03和04班。表1中的课程ID 03和04是我需要返回的(学生03没有参加的所有课程)。我试过很多次,最后一次是:

SELECT table1.* FROM table1
LEFT JOIN table2
ON
    table1.course_ID = table2.course_ID
WHERE
    table2.course_ID IS NULL
AND 
    table2.user_ID != 3

感谢你的帮助!
表1
| 课程ID|课程名称|
| - -----|- -----|
| 01|数学|
| 02|英语|
| 03|艺术|
| 04|音乐|
表2
| 证书ID|课程ID|用户ID|
| - -----|- -----|- -----|
| 01| 01| 03|
| 02| 02| 03|

slsn1g29

slsn1g291#

根据您当前的要求,下面的查询将工作

SELECT * FROM table1 t1 
    WHERE course_ID 
    NOT IN (SELECT course_ID FROM table2 WHERE user_ID =3)

如果table2中有更多的记录,并且需要填充多个学生的详细信息,则必须使用其他逻辑
如果你想修改你的查询,那么使用如下

SELECT table1.* FROM table1 
         LEFT JOIN table2 ON table1.course_ID = table2.course_ID 
         AND table2.user_ID = 3 
    WHERE table2.course_ID IS NULL
flseospp

flseospp2#

select t1.* from table1 as t1
left join table2 as t2 on t2.course_ID = t1.course_ID and t2.user_ID = 3 
where t2.user_ID is null;

为了获得更可读的查询,如果可用,可以使用EXCEPT

select * from table1
except
select t1.* from table1 as t1
inner join table2 as t2 on t2.course_ID = t1.course_ID and t2.user_ID = 3;

相关问题