Rameez Rami Rameez Rami - 7 months ago 46
MySQL Question

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

tags structure

enter image description here


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

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.