简体   繁体   中英

MySQL: A bit complex query is returning count results wrong

There are these three tables:

posts
posts_replies
likes

This query is returning me data almost fine but for some reason the COUNT of Replies on Posts is not accurate.

SELECT posts.title, posts.num, posts.status, posts.category, posts.content, posts.member_num, COUNT( posts_replies.post_num ) AS count, COUNT( likes.comment_num ) AS likes_count
FROM posts_replies
INNER JOIN posts ON ( posts_replies.post_num = posts.num )
LEFT JOIN likes ON ( likes.comment_num = posts_replies.num )
WHERE posts.status =1
AND posts.access = 'Public'
GROUP BY posts.num
ORDER BY count DESC
LIMIT 50

This is the count that i am using: COUNT( posts_replies.post_num ) AS count

Any advices on this?

Thank you

Your query will count each reply once for each like linked to that reply.

In order to count each reply just once, replace

COUNT( posts_replies.post_num ) AS count

with

COUNT(DISTINCT posts_replies.num ) AS count

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM