Count related entities after joining through the bridge.
Section: Many-to-many joins
Aggregate across a many-to-many relationship
sql
sql
SELECT p.post_id, p.title, COUNT(pt.tag_id) AS tag_count
FROM posts p
LEFT JOIN post_tags pt ON pt.post_id = p.post_id
GROUP BY p.post_id, p.title;Explanation
Use `LEFT JOIN` if you want posts with zero tags to remain visible.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Many-to-many joins
Join through a bridge table
Resolve many-to-many relationships with two joins.
Find posts with all required tags
Join and group, then compare distinct matched tags to the required count.