我有3个表:users
,courses
和courseusers
。 Courseusers是连接courses.idCourse与users.idUser的中间表。但是,中间表没有外键约束ON DELETE CASCADE
或ON UPDATE CASCADE
。
Users:
idUser|name
Courses:
idCourse|name
Courseusers:
id|idUser|idCourse
我的问题是,我如何获得前3个订阅最多的课程(courseuser
中的大多数条目),同时忽略users
和courses
表中手动删除的用户(他们将仍然作为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
答案 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