You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 11:54:02