多个表上的Mysql COUNT(*)

时间:2009-06-03 10:44:24

标签: sql mysql

此查询出了什么问题:

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'的附加列,它显示了该course_id的modules表中的记录数,另一个名为'vidCount',它对视频表执行相同的操作。

错误:

  

错误号码:1064

     

您的SQL语法有错误;   检查对应的手册   您的MySQL服务器版本   正确的语法在“”附近使用   moduleCount,vid.COUNT()作为vidCount   从作为co的课程,'在第1行

5 个答案:

答案 0 :(得分:46)

使用子选择,你可以这样做:

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

答案 1 :(得分:12)

我有更好的解决方案和轻松

SELECT COUNT(*),(SELECT COUNT(*) FROM table2) FROM table1

答案 2 :(得分:3)

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

答案 3 :(得分:1)

SELECT co.*, m.ModCnt as moduleCount, v.VidCnt as vidCount 
FROM courses co
INNER JOIN (
        select count(*) AS ModCnt, co.id AS CoID
        from modules 
        group by co) m
    ON m.CoID = co.id
INNER JOIN (
        select count(*) AS VidCnt, co.id AS CoID
        from videos
        group by co) v
    ON v.CoID = co.id   
INNER JOIN videos vid 
    ON vid.course_id = co.id 
ORDER BY co.id DESC

答案 4 :(得分:-2)

拍这个。我用一些非mysql代码完成了这项工作:

function getAllWithStats($info='*',$order='',$id=0)
{
    $courses=$this->getAll($info,$order,$id);

    foreach ($courses as $k=>$v)
    {
        $courses[$k]['modCount']=$this->getModuleCount($v['id']);
        $courses[$k]['vidCount']=$this->getVideoCount($v['id']);
    }

    return $courses;
}