I have 3 tables: 'cards', 'tags' and 'cardstags', where cards HABTM tags
Question: What query do I execute on the 'tags' table to count the number of associated 'cards' rows?
I'm looking for somet开发者_开发问答hing like this:
tags.name | count
----------+------
cricket | 15 (15 cards are tagged as 'cricket')
soccer | 23
football | 12
select tags.name, count(*) from tags join cardstags
on tags.id=cardstags.tag_id group by tags.name
If you want only those tags that have at least one card:
select tags.name, count(cardstags.tag_id) from tags inner join cardstags on tags.id=cardstags.tag_id group by tags.id;
To include tags with no cards, use a left join instead of an inner join.
精彩评论