[英]How to perform left joins on multiple tables along with aggregate functions
SELECT
posts.id,posts.user_id,
username, title,posts.body as post_body, posts.created_at, posts.is_open, posts.views as views, users.photoUrl,
COUNT(DISTINCT answers.id) as answer_count,
COUNT(DISTINCT comments.id) as comment_count,
COUNT (CASE answers.approved WHEN 1 THEN 1 ELSE null END) as correct_count,
GROUP_CONCAT(tagname) as tags
FROM posts
LEFT JOIN posttag ON posts.id = post_id
JOIN tags ON tag_id = tags.id
JOIN users ON user_id = users.id
LEFT JOIN answers ON answers.post_id = posts.id
LEFT JOIN comments ON posts.id = comments.post_id
WHERE posts.id = ?;
我正在尝试使用相应的答案、评论和标签来查询每个帖子。
但是在我的查询结果中,当有 4 个标签时,我得到 8 个标签
COUNT correct_count 从 1 变为 4
我怎样才能得到正确的数据?
对correct_count
和tags
也使用DISTINCT
:
.....................................
COUNT(DISTINCT CASE WHEN answers.approved THEN answers.id END) as correct_count,
GROUP_CONCAT(DISTINCT tagname) as tags
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.