I’m selecting posts from a ‘posts’ table in a MySQL database, but I want one of the columns returned to be a comment count from a comments table using the rows selected post id. My DB is relational so the comment table has a post id field (comment_post_id). Here’s what I have, but this query is creating a syntax error in PHPMYAdmin:
SELECT post_id, post_title, post_status, post_image, post_tags, post_views, post_date, user_name, cat_title,
COUNT(SELECT comment_id FROM comments WHERE comment_post_id = post_id) AS comment_count
FROM posts
LEFT JOIN users ON post_author = user_id
LEFT JOIN categories ON post_category_id = cat_id
ORDER BY post_id DESC
Post and Comments table columns are laid out as follows:
Post:
post_id, post_title, post_status, post_image, post_tags, post_views, post_date, post_author, post_category_id
Comments:
comment_id, comment_post_id, comment_content
2
Answers
You could join
comments
withpost
then usecount(comment_id)
. Instead of redundant sub query.You can use this query to get the count here. Try this way