Mysql COUNT(*) on multiple tables

后端 未结 5 712
我寻月下人不归
我寻月下人不归 2020-12-23 22:55

What\'s wrong with this query:

SELECT co.*, mod.COUNT(*) as moduleCount, vid.COUNT(*) as vidCount 
 FROM courses as co, modules as mod, videos as vid 
 WHERE         


        
相关标签:
5条回答
  • 2020-12-23 23:32

    Using subselects you can do:

    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
    

    But be carefull as this is an expensive query when courses has many rows.

    EDIT: If your tables are quite large the following query should perform much better (in favor of being more complex to read and understand).

    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
    
    0 讨论(0)
  • 2020-12-23 23:39
    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
    
    0 讨论(0)
  • 2020-12-23 23:40
    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
    
    0 讨论(0)
  • 2020-12-23 23:41

    i have better solution and easy

    SELECT COUNT(*),(SELECT COUNT(*) FROM table2) FROM table1
    
    0 讨论(0)
  • 2020-12-23 23:43

    Shoot this. I did the job with some non-mysql code:

    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;
    }
    
    0 讨论(0)
提交回复
热议问题