只有两个相关表中存在时,才能在具有多个多关系的中间表上进行SELECT count(*)

时间:2012-09-07 07:34:20

标签: mysql sql select many-to-many

我有3个表: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

4 个答案:

答案 0 :(得分:3)

http://sqlfiddle.com/#!2/0567a/1

SELECT
  c.name,
  COUNT(1) AS total
FROM Courceusers cu
JOIN Cources c USING(idCource)
JOIN Users u USING(idUser)
GROUP BY 1
ORDER BY 2 DESC
LIMIT 3;

答案 1 :(得分: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 

答案 2 :(得分:1)

根据表Users加入所有不在中间表

上的表
SELECT  a.idUser, a.Name, COUNT(c.idCourse) totalCount
FROM    Users a
            INNER JOIN  CourseUsers b
                ON a.idUser = b.idUser
            INNER JOIN Courses c
                ON b.idCourse = c.idCourse
GROUP BY a.idUser, a.Name
ORDER BY totalCount DESC
LIMIT 3

答案 3 :(得分:1)

select 
    CourseUsers.idCourse, 
    Courses.name, 
    COUNT(distinct CourseUsers.idUser) as Subscribers
from CourseUsers
    inner join Courses on CourseUsers.idCourse = Courses.idCourse
    inner join Users on CourseUsers.idUser = Users.idUser
group by CourseUsers.idCourse, Courses.name
order by Subscribers desc
limit 3