I have two tables,
- Labels -> id,name,description, user, status
- Label_connection. -> id, Label_id, categories
So there are multiple categories, let's say 1 => new, 2 => old.
I need the counts of the child table according to the category.
This is what I have right now,
SELECT `L`.*, COUNT(DISTINCT LC1.id) as count1, COUNT(DISTINCT LC2.id) as count2
FROM (`Labels` L)
LEFT JOIN `Label_connection` LC1 ON `LC1`.`Label_id` = `L`.`id` AND LC1.categories = "1"
LEFT JOIN `Label_connection` LC2 ON `LC2`.`Label_id` = `L`.`id` AND LC2.categories = "2"
WHERE `L`.`status` = '0' AND `L`.`user` = 1
GROUP BY `L`.`id`
ORDER BY `L`.`id` DESC
LIMIT 20
This does get me the counts correctly, But I am concerned about the multiple joins, as the number of categories will go up.
If anybody can improve this I would be grateful,
Thanks in advance.