题
就获取“线程”拥有的子级数量而言,这是有效的,但现在我似乎无法让它拉动父行列。父行有 parent_id is null
, ,树可以是任意深度。
我设法用两个单独的查询来完成此操作,但必须有一种方法只使用一个查询并获取子项的数量:
with recursive all_comments as (
select id, parent_id, id as root_id
from comment
where parent_id is null
union all
select c.id, c.parent_id, p.root_id
from comment c
join all_comments p on c.parent_id = p.id
)
select root_id, count(*) as comment_count
from all_comments
group by root_id;
我该如何拉 content
来自父级的列 comment
在这个小提琴中?
解决方案
选项1
包括附加列(仅 content
在示例中)立即在 rCTE 的每次迭代中。你必须 GROUP BY
另外,它(它们)是外部 SELECT。
显然,你不想计算父母,所以立即加入第一层孩子:
WITH recursive tree AS (
SELECT p.id AS root_id, c.id, p.content
FROM comment p
LEFT JOIN comment c ON c.parent_id = p.id
WHERE p.parent_id IS NULL
UNION ALL
SELECT p.root_id, c.id, p.content
FROM tree p
JOIN comment c ON c.parent_id = p.id
)
SELECT root_id, content, count(id) AS comment_count
FROM tree
GROUP BY 1, 2
ORDER BY 1;
为了保护父母而不让任何孩子使用 LEFT JOIN
在基地 SELECT
的 RCTE。因此,使用 count(id)
在外 SELECT
忽略由此产生的 NULL 值。
选项2
对于非常深的树或大的附加列,仅检索 rCTE 中的 ID 并连接到表可能会更便宜 comment
再次在外面 SELECT
检索更多列:
WITH RECURSIVE tree AS (
SELECT p.id AS root_id, c.id
FROM comment p
LEFT JOIN comment c ON c.parent_id = p.id
WHERE p.parent_id IS NULL
UNION ALL
SELECT p.root_id, c.id
FROM tree p
JOIN comment c ON c.parent_id = p.id
)
SELECT p.*, c.content -- add more columns?
FROM (
SELECT root_id, count(id) AS comment_count
FROM tree
GROUP BY 1 -- cheaper ...
) p
JOIN comment c ON c.id = p.root_id -- ... but additional join
ORDER BY p.root_id;
你的小提琴有两个错误。考虑这个固定的 SQL小提琴.
其他提示
你的小提琴打不开,所以我不确定我是否正确理解你拥有什么和你想要什么,但我斗胆猜测你需要重新加入 comment
在 id
, ,像这样:
with recursive all_comments as (
select id, parent_id, id as root_id
from comment
where parent_id is null
union all
select c.id, c.parent_id, p.root_id
from comment c
join all_comments p on c.parent_id = p.id
)
select a.root_id, a.comment_count, com.content from
(select root_id, count(*) as comment_count
from all_comments
group by root_id) as a
inner join
comment as com
on a.root_id = com.id and com.parent_id is null;
不隶属于 dba.stackexchange