I want to build SQL query with good performance approach. I need to select all categories and count bands associated with this categories.
Structure:
bands:
id | band_name |cat_id
----------|----------------|------------
1 | Business 1 | 1
2 | Business 12 | 2
3 | Business 123 | 2
categories:
id | name
----------|----------------
1 | Business 1
2 | Business 12
3 | Business 123
connections:
id | band_id |cat_id
----------|----------------|------------
1 | 1 | 1
2 | 2 | 1
3 | 2 | 1
Query:
SELECT c.name AS category_name, (SELECT COUNT(icc.band_id) FROM cms_bands_categories_connections AS icc RIGHT JOIN cms_bands AS ib ON icc.band_id = ib.id) AS bands_sum FROM
cms_bands_categories AS c
JOIN cms_bands_categories_connections AS cc ON
c.id = cc.category_id
GROUP BY
c.id
Results are very strange - bands_sum is evual to 3 in each row. Don't blame my structure - I had to modyfi it becouse of requirements specification change.