我的查询在我想要 0 的地方返回 null。我认为这与子查询内部的合并有关,但我无法进行任何更改。有问题的查询:
SELECT c.post_id, c.post_name, c.post_content, c.post_datetime, c.user_name,
p.like_count,
p.dislike_count,
s.comment_count
FROM posts c
LEFT JOIN (
select post_id,
sum(like_count) like_count,
sum(dislike_count) dislike_count
from post_likes
group by post_id
) p ON c.post_id = p.post_id
LEFT JOIN (
select post_id, COALESCE(sum(comment_count),0) comment_count
from comments
group by post_id
) s ON c.post_id = s.post_id
WHERE c.user_name = 'test'
它返回正确的总和,但 COALESCE 似乎没有影响。
最佳答案
你的怀疑是正确的。将 COALESCE
向上移动到外部查询,您应该会很好。它不起作用的原因是 COALESCE
仅适用于 s
派生表表达式中的行。如果在 s
中没有来自与 c
的左外连接的匹配行,则 s
中的任何内容(包括合并的列)都不会从 s
。您将获得所有列的 NULL。
关于mysql - 在连接和子查询中合并的 SQL 查询返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33382396/