一尘不染

多个表上的MySQL COUNT(*)

sql

此查询出了什么问题:

SELECT co.*, mod.COUNT(*) as moduleCount, vid.COUNT(*) as vidCount 
 FROM courses as co, modules as mod, videos as vid 
 WHERE mod.course_id=co.id AND vid.course_id=co.id ORDER BY co.id DESC

换句话说,我该如何处理从“课程”返回的每条记录,又有一个名为“ modCount”的列,该列显示了该课程ID的模块表中的记录数,还有一个名为“
vidCount”的列视频表也一样。

错误:

错误号:1064

您的SQL语法有误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第1行附近使用’
)作为moduleCount,vid.COUNT( )作为vidCount FROM course as co,’


阅读 147

收藏
2021-03-17

共1个答案

一尘不染

使用子选择,您可以执行以下操作:

SELECT co.*, 
    (SELECT COUNT(*) FROM modules mod WHERE mod.course_id=co.id) AS moduleCount, 
    (SELECT COUNT(*) FROM videos vid WHERE vid.course_id=co.id) AS vidCount
FROM courses AS co
ORDER BY co.id DESC

但是要小心,因为当课程有很多行时,这是一个昂贵的查询。

编辑: 如果您的表很大,下面的查询应该执行得更好(有利于更复杂地阅读和理解)。

SELECT co.*, 
    COALESCE(mod.moduleCount,0) AS moduleCount,
    COALESCE(vid.vidCount,0) AS vidCount
FROM courses AS co
    LEFT JOIN (
            SELECT COUNT(*) AS moduleCount, course_id AS courseId 
            FROM modules
            GROUP BY course_id
        ) AS mod
        ON mod.courseId = co.id
    LEFT JOIN (
            SELECT COUNT(*) AS vidCount, course_id AS courseId 
            FROM videos
            GROUP BY course_id
        ) AS vid
        ON vid.courseId = co.id
ORDER BY co.id DESC
2021-03-17