Say I have two tables: cat_collection and cat_mapping
cat_mapping contains three fields; id, collection_id, and post_id
I would like to be able to select all names from cat_collection
SELECT name FROM cat_collection
as well as the number of times they are referenced in cat_mapping
So if cat_collection contained
| id | | name |
0 cat1
1 cat2
and cat_mapping contained
| id | | collection_id | | post_id |
0 1 0
1 1 1
how can I return
| name | | count |
cat1 0
cat2 2
solution
SELECT cc.name, (
SELECT COUNT( cm.collection_id )
FROM cat_mapping AS cm
WHERE cm.collection_id = cc.id
) AS `count`
FROM cat_collection AS cc
I think a subquery like this would do it: