PostgreSQL递归CTE查询评论子评论继承父评论用户信息错误如何解决
问题根因
你递归查询UNION ALL分支中,关联用户表的关联条件写错了。当前你用的是父评论output_comments的user_id去关联用户表,所以查询到的永远是父评论的创建者名称,没有取当前子评论自身的创建者信息。
修复后的SQL
仅需要修改UNION ALL分支中用户表的关联字段,用子评论自身的user_id匹配即可:
with recursive output_comments as ( select c.id, c.body, c.parent_id, c.reference_id, c.user_id, u.name as user_name from comments c left join users u on c.user_id = u.id where reference_id = 'test' and parent_id is null union all select c.id, c.body, c.parent_id, c.reference_id, c.user_id, u.name as user_name from output_comments inner join comments c on output_comments.id = c.parent_id left join users u on c.user_id = u.id -- 此处修改为子评论的user_id关联用户表 ) select * from output_comments;
执行上述语句即可得到和你预期完全一致的查询结果,子评论会正确匹配到自身创建者whitman的信息。
内容的提问来源于stack exchange,提问作者ElPapi42
相关产品推荐
相关产品推荐

