我的第一个查询返回前10条注释,其parent_id为空
SELECT comment_id FROM comments WHERE thread_id = $1
AND parent_id is NULL
ORDER BY upvoted DESC FETCH FIRST 10 ROW ONLY
我将如何使用每个注释ID来执行递归查询?
我当前的方法是将返回的comment_id存储在数组中
[1, 2, 3, 4, 10, 14, 15, 18, 19, 20]
,然后使用for循环对每个id进行递归查询
var query =
`With RECURSIVE cte AS
(
SELECT * FROM comments WHERE comment_id = $1
UNION
SELECT t.*
From comments t
JOIN cte rt ON rt.comment_id = t.parent_id
)
SELECT * FROM cte`;
for(int i = 0; i < array.size(); i++){
client.query(query, array[i])
. . .
}
所以我想知道如何在单个查询中做到这一点,而不是将ID存储在数组中,然后递归查询每个ID?
答案 0 :(得分:1)
您可以将第一个语句用作递归查询的非递归部分。但是由于需要的顺序,您需要将该查询放在括号之间:
With RECURSIVE cte AS
(
(
SELECT *
FROM comments
WHERE thread_id = $1
AND parent_id is NULL
ORDER BY upvoted DESC
FETCH FIRST 10 ROW ONLY
)
UNION
SELECT t.*
From comments t
JOIN cte rt ON rt.comment_id = t.parent_id
)
SELECT * FROM cte`
或者,您也可以在单独的CTE中进行此操作:
With RECURSIVE root_nodes AS
(
SELECT *
FROM comments
WHERE thread_id = $1
AND parent_id is NULL
ORDER BY upvoted DESC
FETCH FIRST 10 ROW ONLY
), cte as (
select *
from root_nodes
UNION
SELECT t.*
From comments t
JOIN cte rt ON rt.comment_id = t.parent_id
)
SELECT *
FROM cte;
请注意,即使第一个CTE不是递归关键字,recursive
关键字也属于WITH
。