简体   繁体   中英

how to fetch count of items in relation table in mysql

i have two mysql db tables 'tags' and 'tags_used'. i have added images for checking the db structure.currently iam using laravel fluent query builder. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM