Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the comment count of the post through mysql query?

Tags:

mysql

I would like to get numbers of comments for each posts using mysql.

I have two tables, one is post table and the other is comment table. Post table has id, title and content field while comment has id, post_id, author and comment field.

The result that would like to achieve is like

---------------------------------------------
Title               Comment Count
---------------------------------------------
My fancy post             2
---------------------------------------------

Let me know if you have confusion about my question.

like image 299
Johndave Decano Avatar asked Dec 11 '25 09:12

Johndave Decano


1 Answers

SELECT
    a.title,
    COUNT(b.post_id) AS 'Comment Count'
FROM
    post a
LEFT JOIN
    comment b ON a.id = b.post_id
GROUP BY
    a.id

This will account for posts that don't have any comments.

like image 79
Zane Bien Avatar answered Dec 13 '25 07:12

Zane Bien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!