在PostgreSQL中将值插入数组

时间:2014-07-23 16:04:06

标签: sql arrays postgresql common-table-expression recursive-query

我正在尝试将值插入整数数组,用作显示特定节点的所有祖先的路径。

这些值(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

任何提示或想法?

2 个答案:

答案 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];"