我有桌子,看起来像那样
id parent_id
1 null
2 1
3 2
4 1
5 3
对于表中的每一行,我想检索有关其父项的信息(从第一代到第N代)。这意味着,如果id = 3
行parent_id = 2
且id = 2
行parent_id = 1
,则3
属于2
和1
好。
我想得到的结果:
id multi_level_parent_id
1 null
2 1
3 2
3 1
4 1
5 3
5 2
5 1
我认为,我必须使用递归select
。我编写了SQL代码,但它仅返回有关第一代
WITH Rec AS
(
SELECT *
FROM MyTable t
UNION ALL
SELECT *
FROM MyTable t
INNER JOIN Rec r ON t.id = r.parent_id
)
SELECT *
FROM Rec
有人知道如何检索信息,我需要什么?
答案 0 :(得分:3)
这就是你所追求的:
WITH Rec
AS (
SELECT id,
id AS parent_id,
0 AS steps
FROM MyTable t
UNION ALL
SELECT r.id,
t.parent_id,
r.steps + 1 AS steps
FROM MyTable t
INNER JOIN Rec r ON t.id = r.parent_id)
SELECT id,
parent_id
FROM MyTable
WHERE parent_id IS NULL
UNION ALL
SELECT id,
parent_id
FROM Rec
WHERE parent_id <> id
ORDER BY id;
和结果: