SQL 在连接内部合并查询,子查询返回 null

SQL Query with coalesce inside join and subquery returning null

我的查询在我想要 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 派生的 table 表达式中的行。如果 s 中没有来自与 c 的左外连接的匹配行,那么来自 s 的任何内容,包括合并的列,都不会来自 s return。您将获得所有列的 NULL。