【发布时间】:2021-11-02 12:05:25
【问题描述】:
我有一个 cmets 的递归模型,其中 cmets 归用户所有,每个评论都与一个 cmets 列表相关,作为他们的回复,这是一个用于重现此数据库的 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
它返回类似这样的东西:
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 炼金术士,所以我决定寻求帮助,谢谢!
【问题讨论】:
-
left join users u on c.user_id = u.id,在递归部分。
标签: sql database postgresql common-table-expression recursive-query