Counting a child table with foreign key, multiple times, with condition Counting a child table with foreign key, multiple times, with condition codeigniter codeigniter

Counting a child table with foreign key, multiple times, with condition


For conditional aggregation, you can also use COUNT DISTINCT .. CASE..WHEN..END.

Also, your current query is not valid GROUP BY (unless L.id is a primary key). For details, read: Error related to only_full_group_by when executing a query in MySql

Also, please prefer to use SQL-Standard single quotes around String literals instead of double quotes.

SELECT L.id,         COUNT(DISTINCT CASE WHEN LC.categories = '1' THEN LC.id END) AS count1,        COUNT(DISTINCT CASE WHEN LC.categories = '2' THEN LC.id END) AS count2 FROM Labels AS LLEFT JOIN Label_connection AS LC   ON LC.Label_id = L.idWHERE L.status = '0' AND      L.user = 1GROUP BY L.id ORDER BY L.id DESC LIMIT 20


You could try writing it as one JOIN with conditional aggregation:

SELECT `L`.*     , SUM(CASE WHEN LC.categories = "1" THEN 1 END) as count1     , SUM(CASE WHEN LC.categories = "2" THEN 1 END) as count2FROM `Labels` LLEFT JOIN `Label_connection` LC ON `LC`.`Label_id` = `L`.`id`WHERE `L`.`status` = '0' AND `L`.`user` = 1GROUP BY `L`.`id` ORDER BY `L`.`id` DESC LIMIT 20