You are missing the GROUP BY
clause, and since MySQL is lenient about aggregate functions and columns in the SELECT
not appearing in the group by, it collapses down to one row showing the total count, but mixed column values from other columns.
SELECT bp.*, COUNT(bpc.id) AS post_comments
FROM blog_posts AS bp
LEFT JOIN blog_post_comments AS bpc ON bpc.post_id = bp.id
GROUP BY bp.id
LIMIT 0, 10
The more portable way to do this for RDBMS other than MySQL would be to join against a subquery that returns only the post_id
and the number of posts per id, allowing the rest of the columns from blog_posts
to be selected without appearing in the GROUP BY
.
SELECT
bp.*,
bcount.counts
FROM
blog_posts AS bp
LEFT JOIN (
SELECT post_id, COUNT(*) AS counts
FROM blog_post_comments
GROUP BY post_id
) bcounts ON bp.id = bcounts.post_id