[英]how to fetch count of items in relation table in mysql
i have two mysql db tables 'tags' and 'tags_used'. 我有两个mysql数据库表'tags'和'tags_used'。 i have added images for checking the db structure.currently iam using laravel fluent query builder.
我已经添加了用于检查数据库结构的图像。当前使用laravel流利的查询生成器访问iam。 Now what i want to query is the count of rows in relation table like below.
现在我要查询的是关系表中的行数,如下所示。 Please help me with either laravel fluent query or plain sql query.
请使用laravel流利查询或纯SQL查询来帮助我。
id | name |times_used
------------
1 | tag1 | 3
------------
2 | tag2 | 1
------------
3 | tag3 | 5
------------
4 | tag4 | 1
------------
5 | tag5 | 0
------------
----------
Use a LEFT JOIN
between the tables, and COUNT()
to count the matches. 在表之间使用
LEFT JOIN
,然后使用COUNT()
对匹配进行计数。
SELECT t.id, t.name, IFNULL(COUNT(u.id), 0) AS times_used
FROM tags AS t
LEFT JOIN tags_used AS u ON t.id = u.tags_id
GROUP BY t.id
Note that you have to use COUNT(u.id)
rather than COUNT(*)
so you don't count the row with null values in the tags_used
columns when there's no matches. 请注意,您必须使用
COUNT(u.id)
而不是COUNT(*)
这样在没有匹配项的情况下,就不会在tags_used
列中使用具有空值的行进行计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.