我有三张桌子:userscoursescourseusers。Courseusers是连接courses.idCourse和users.idUser的中间表。但是,中间表没有外键约束和ON DELETE CASCADEON UPDATE CASCADE

Users:
idUser|name

Courses:
idCourse|name

Courseusers:
id|idUser|idCourse

我的问题是,如何获得前3个最订阅的课程(大多数在courseuser中的条目),而忽略了从userscourses表中手动删除的用户(它们仍然存在作为courseuser中的条目)。
我现在所拥有的:
SELECT c.idCourse, c.name, count(*) as count
FROM courseusers as cu
     JOIN course as c
         ON cu.idCourse=c.idCourse
     JOIN users as usr
         ON (usr.idUser=u.idUser)
GROUP BY u.idCourse
ORDER BY count DESC
LIMIT 3

最佳答案

尝试使用以下查询

SELECT c.idCourse, c.name, count(*) as count
FROM courseusers as cu
   LEFT JOIN course as c
       ON cu.idCourse=c.idCourse
   LEFT JOIN users as usr
       ON (usr.idUser=u.idUser)
GROUP BY u.idCourse
ORDER BY count DESC
LIMIT 3

关于mysql - 仅在两个相关表中都存在的情况下,具有许多关系的中间表上的SELECT count(*),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12313739/

10-10 22:07