我有一个表组织,其中有“id”,“parent_id” 我需要在 redshift 表中找到“id”列的超级父 id 。
输入表:
id | parent_id |
---|---|
a1 | 空 |
b1 | c1 |
c1 | a1 |
d1 | 空 |
输出表:
id | parent_id | super_parent_id |
---|---|---|
a1 | 空 | 空 |
b1 | c1 | a1 |
c1 | a1 | a1 |
d1 | 空 | 空 |
我已经尝试过了
with RECURSIVE ParentHierarchy(id, parent_id, super_parent_id) AS (
SELECT id, parent_id, id AS super_parent_id
FROM org
WHERE parent_id IS NULL
UNION ALL
SELECT t.id as id , t.parent_id as parent_id, ph.super_parent_id as super_parent_id
FROM org t
JOIN ParentHierarchy ph ON t.parent_id = ph.id
)
SELECT ph.id, ph.parent_id, ph.super_parent_id AS super_parent_id
FROM ParentHierarchy ph
我无法得到预期的结果。你能纠正我吗?
提前致谢
您的查询几乎是正确的;唯一需要的调整是仅当父项不为空时才选择 super_parent_id :
WITH RECURSIVE ParentHierarchy(id, parent_id, super_parent_id) AS (
SELECT id, parent_id, id AS super_parent_id
FROM org
WHERE parent_id IS NULL
UNION ALL
SELECT t.id as id , t.parent_id as parent_id, ph.super_parent_id as super_parent_id
FROM org t
JOIN ParentHierarchy ph ON t.parent_id = ph.id
)
SELECT id, parent_id, CASE WHEN parent_id IS NOT NULL THEN super_parent_id ELSE NULL END AS super_parent_id
FROM ParentHierarchy ph
ORDER BY id;
我建议使用自连接查询而不是递归查询:
SELECT O1.id, o1.parent_id, COALESCE(o2.parent_id, o2.id) AS super_parent_id
FROM org o1
LEFT JOIN org o2 ON o1.parent_id = o2.id