【问题标题】:Update a table recursively in Postgres在 Postgres 中递归更新表
【发布时间】:2015-07-28 05:48:47
【问题描述】:

我正在尝试使用递归更新表(具有树结构)。我使用以下代码(唯一的区别是不使用更新部分,最后选择查询来自 CTE 而不是原始表)来显示任何给定节点的子树,在这种情况下,它是硬编码的 'G '。

我现在需要更新子树的值,但是使用下面的代码我遇到了一个无法识别原因的错误。更新查询附近给出了系统税错误。

WITH RECURSIVE ph AS
(
    -- Anchor
    SELECT attr1, attr3, attr4
    FROM entity
    WHERE attr3 = 'G'

    UNION ALL

    -- Recursive Member
    SELECT entity.attr1, entity.attr3, entity.attr4
    FROM entity, ph     
    WHERE ph.attr1 = entity.attr3

    -- update original table (not the cte)
    UPDATE entity
    SET attr4 = entity.attr4 * 1.1
    FROM ph
    WHERE ph.attr1 = entity.attr3;
)

    --see result with updated values
    Select * from entity;

已通过以下查询解决。

WITH RECURSIVE ph AS
(
    -- Anchor
    SELECT attr1, attr3, attr4
    FROM entity
    WHERE attr3 = 'E'

    UNION ALL

    -- Recursive Member
    SELECT entity.attr1, entity.attr3, entity.attr4
    FROM entity, ph     
    WHERE ph.attr1 = entity.attr3
)

    --see result with updated values
    UPDATE entity
    SET attr4 = attr4 * 100
    WHERE attr1 IN (SELECT attr1 FROM ph)
    RETURNING *;

【问题讨论】:

  • update 移到 cte 之外(您当前拥有 select * from entity 的位置)

标签: sql postgresql recursion


【解决方案1】:

UPDATE 不能是递归 SELECT 的一部分。您需要使用 SELECT 的结果进行更新:

WITH RECURSIVE ph AS
(
    -- Anchor
    SELECT attr1, attr3, attr4
    FROM entity
    WHERE attr3 = 'G'

    UNION ALL

    -- Recursive Member
    SELECT entity.attr1, entity.attr3, entity.attr4
    FROM entity, ph     
    WHERE ph.attr1 = entity.attr3

)
    -- update original table (not the cte)
    UPDATE entity
    SET attr4 = entity.attr4 * 1.1
    FROM ph
    WHERE ph.attr1 = entity.attr3;

--see result with updated values
Select * from entity;

【讨论】:

  • 经过一段时间的研究,我解决了这个问题。正如您所说,更新可以是递归选择的一部分。请参阅问题末尾对问题解决方式的更正。 Tks
猜你喜欢
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
相关资源
最近更新 更多