我正在尝试将值插入整数数组,用作显示特定节点的所有祖先的路径。
这些值(parent_link integer
)来自ID为parent_link
的表格。我试图遍历树状结构以组装路径中的所有parent_link
以插入属于该特定ID的整数数组。我正在尝试为我的数据库中的每个记录执行此操作。到目前为止,我有:
INSERT INTO master_ifis_network (path)
SELECT t2.parent_link
FROM master_ifis_network as t2
WHERE t2.parent_link = (SELECT t1.parent_link
FROM master_ifis_network as t1)
AND t2.link_id = (parent_link)
我收到一条错误消息,指出我无法在预期integer
的位置插入integer[]
。
我也试过这个,它输出一个父节点列表:
SELECT parentX.parent_link FROM [table name] as nodeX, [table name] as parentx
WHERE nodeX.left BETWEEN parentX.left AND parentX.right)
AND nodeX.link_id = [some id]
ORDER BY parentX.left DESC
任何提示或想法?
答案 0 :(得分:2)
使用递归CTE,即:WITH RECURSIVE
您需要UPDATE
,而不是INSERT
:
WITH RECURSIVE cte AS (
SELECT link_id, ARRAY[parent_link] AS path, 1 AS level
FROM master_ifis_network
UNION ALL
SELECT c.link_id, m.parent_link || c.path, c.level + 1
FROM cte c
JOIN master_ifis_network m ON m.link_id = c.path[1]
)
UPDATE master_ifis_network m
SET path = sub.path
FROM (
SELECT DISTINCT ON (link_id) *
FROM cte
ORDER BY link_id, level DESC
) sub
WHERE m.link_id = sub.link_id;
相关答案:
这里还有很多其他人。使用以上关键词搜索。
答案 1 :(得分:0)
以下是我最终的结果:
UPDATE master_ifis_network SET path = array(SELECT parentX.parent_link
FROM master_ifis_network AS parentX
WHERE (nodeX.left BETWEEN parentX.left AND parentX.right) AND nodeX.link_id = [some id]
ORDER BY parentX.left DESC)
WHERE link_id = [same id];"