我正在尝试使用递归更新表(具有树结构)。我使用下面的代码(唯一的区别是不使用更新部分以及CTE的最后选择查询而不是原始表)来显示任何给定节点的子树,在这种情况下它是硬编码的&# 39; G&#39 ;.
我现在需要更新子树的值但是使用下面的代码我遇到了一个错误,导致无法识别。更新查询附近发生systax错误。
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 *;
答案 0 :(得分:5)
UPDATE
不能成为递归 SELECT 的一部分。您需要使用SELECT的结果进行UPDATE:
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;