1

我有 3 个表userscoursescourseusers。Courseusers 是连接 courses.idCourse 和 users.idUser 的中间表。但是,中间表没有外键约束 and ON DELETE CASCADEor ON UPDATE CASCADE

Users:
idUser|name

Courses:
idCourse|name

Courseusers:
id|idUser|idCourse

我的问题是,我如何获得订阅最多的前 3 门课程( 中的大多数条目),同时忽略和表courseuser中手动删除的用户(它们仍将作为条目存在)。userscoursescourseuser

我现在拥有的:

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

4 回答 4

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 
于 2012-09-07T08:28:20.303 回答
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;
于 2012-09-07T07:37:21.427 回答
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
于 2012-09-07T08:25:23.123 回答
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
于 2012-09-07T07:42:19.570 回答