开发者

MySQL - counting with HABTM relationships

开发者 https://www.devze.com 2022-12-14 16:15 出处:网络
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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消