递归 SQL 查询从父级到子级的泄漏数据

Recursive SQL query leaking data from parent to child

我有一个评论的递归模型,其中评论归用户所有,每条评论都与评论列表相关作为他们的回复,这是一个用于复制该数据库的 DDL(我使用 postgres:13图片):

CREATE TABLE public.users (
    id varchar NOT NULL,
    "name" varchar NULL,
    CONSTRAINT users_pkey PRIMARY KEY (id)
);

CREATE TABLE public."comments" (
    id uuid NOT NULL,
    body varchar NULL,
    reference_id varchar NULL,
    parent_id uuid NULL,
    user_id varchar NULL,
    CONSTRAINT comments_pkey PRIMARY KEY (id)
);
CREATE INDEX idx_reference_id ON public.comments USING btree (reference_id);
CREATE INDEX idx_user_id ON public.comments USING btree (user_id);

INSERT INTO public.users
(id, "name")
VALUES('0', 'olbert');
INSERT INTO public.users
(id, "name")
VALUES('1', 'whitman');

INSERT INTO public."comments"
(id, body, reference_id, parent_id, user_id)
VALUES('56743f89-648a-4eac-848e-400fd0c777c2'::uuid, 'test comment', 'test', NULL, '0');
INSERT INTO public."comments"
(id, body, reference_id, parent_id, user_id)
VALUES('6ebc4e7b-17c7-413c-ad34-e0c995d9b807'::uuid, 'test comment', 'test', '56743f89-648a-4eac-848e-400fd0c777c2'::uuid, '1');

然后,我尝试使用以下查询递归查询:

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 output_comments.user_id = u.id
) select * from output_comments;

但是发生的是回复得到了父评论的用户,而不是它自己的用户(它的创建者),所以不是返回这样的东西:

56743f89-648a-4eac-848e-400fd0c777c2, test comment, null, test, 0, olbert
6ebc4e7b-17c7-413c-ad34-e0c995d9b807, test comment, 56743f89-648a-4eac-848e-400fd0c777c2, test, 1, whitman

它 returns 是这样的:

56743f89-648a-4eac-848e-400fd0c777c2, test comment, null, test, 0, olbert
6ebc4e7b-17c7-413c-ad34-e0c995d9b807, test comment, 56743f89-648a-4eac-848e-400fd0c777c2, test, 1, olbert

我不是专家 sql 炼金术士,所以我决定寻求帮助,谢谢!

试试这个

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 comments c left join users u on c.user_id = u.id
        inner join output_comments oc on (oc.id= c.parent_id)
) select * from output_comments;

输出: