Mysql COUNT(*) on multiple tables

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 vidCountFROM courses AS coORDER 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 vidCountFROM 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.idORDER BY co.id DESC


你可能感兴趣的:(Mysql COUNT(*) on multiple tables)