我在 PostgreSQL 中有下表,需要获取具有给定 ID 的人的所有祖先。
还需要能够从结果中区分父亲和母亲。
Person table - has about 1M rows, schema looks like this:
+-----+--------+--------+
| id | father | mother |
+-----+--------+--------+
| 1 | 2 | 3 |
| 2 | 4 | 5 |
| 3 | 6 | 7 |
| 4 | 8 | 9 |
| 5 | 10 | 11 |
| ... | ... | ... |
| ... | ... | ... |
+-----+--------+--------+
Run Code Online (Sandbox Code Playgroud)
目前我正在循环进行查询,每个人获得单行。
是否可以在单个查询(或 2 个查询)中获取所有祖先?
查询 id 2 的示例结果:
+----+--------+--------+
| id | father | mother |
+----+--------+--------+
| 2 | 4 | 5 |
| 4 | 8 | 9 |
| 5 | 10 | 11 |
+----+--------+--------+
Run Code Online (Sandbox Code Playgroud)
WITH recursive ParentOf (id, father, mother )
AS
(
-- Anchor query
SELECT id, father, mother
FROM test
WHERE id = ? -- e.g. 2
UNION ALL
-- Recursive query
SELECT t.id, t.father, t.mother
FROM test t
INNER JOIN ParentOf
ON t.id = ParentOf.father OR t.id = ParentOf.mother
)
-- Statement that executes the CTE
SELECT id, father, mother
FROM ParentOf;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |