Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql COUNT(*) on multiple tables

Tags:

sql

mysql

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 mod.course_id=co.id AND vid.course_id=co.id ORDER BY co.id DESC

In other words, how can I do it so with every record returned from 'courses', there's an additional column called 'modCount' which shows the number of records in the modules table for that course_id, and another called 'vidCount' which does the same thing for the videos table.

Error:

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') as moduleCount, vid.COUNT() as vidCount FROM courses as co, ' at line 1

like image 593
Ali Avatar asked Jun 03 '09 10:06

Ali


People also ask

How do I count multiple tables in SQL?

To achieve this for multiple tables, use the UNION ALL. select sum(variableName. aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName; Let us implement the above syntax.

What does count (*) mean in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.

How do I count tables in MySQL?

To check the count of tables. mysql> SELECT count(*) AS TOTALNUMBEROFTABLES -> FROM INFORMATION_SCHEMA. TABLES -> WHERE TABLE_SCHEMA = 'business'; The following output gives the count of all the tables.


2 Answers

i have better solution and easy

SELECT COUNT(*),(SELECT COUNT(*) FROM table2) FROM table1
like image 33
wasim Avatar answered Oct 02 '22 16:10

wasim


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
like image 65
Stefan Gehrig Avatar answered Oct 02 '22 15:10

Stefan Gehrig