如何在多个表上执行左连接以及聚合函数
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 = ?;
我正在尝试查询每个 post 及其相应的答案、评论和标签。
然而在我的查询结果中,当有 4 个标签时我得到 8 个标签
COUNT correct_count 从 1 变为 4
如何获取正确的数据?
对 correct_count
使用 DISTINCT
,对 tags
也使用:
.....................................
COUNT(DISTINCT CASE WHEN answers.approved THEN answers.id END) as correct_count,
GROUP_CONCAT(DISTINCT tagname) as tags
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 = ?;
我正在尝试查询每个 post 及其相应的答案、评论和标签。
然而在我的查询结果中,当有 4 个标签时我得到 8 个标签
COUNT correct_count 从 1 变为 4
如何获取正确的数据?
对 correct_count
使用 DISTINCT
,对 tags
也使用:
.....................................
COUNT(DISTINCT CASE WHEN answers.approved THEN answers.id END) as correct_count,
GROUP_CONCAT(DISTINCT tagname) as tags