Postgres:将更新查询与层次表上的一个查询相结合

时间:2018-05-04 13:58:39

标签: sql postgresql

我有一个分层表,其中每行包含各种父项的ID。更新行(将其设置为活动)意味着我必须更新此行的每个父级。如何将这些查询合并到一个查询中?目前我使用这个不太好的解决方案。我想这可以通过递归CTE完成,但我无法在这里找到正确的方法。提前谢谢!

update areas set active = true  where id = 1000;
update areas set active = true  where id = (select parent1 from areas where id = 1000);
update areas set active = true  where id = (select parent2 from areas where id = 1000);
update areas set active = true  where id = (select parent3 from areas where id = 1000);
update areas set active = true  where id = (select parent4 from areas where id = 1000);

1 个答案:

答案 0 :(得分:2)

基本上你说set active = true如果它是节点本身,parent1,parent2,parent3或parent4,当你通过id查询节点时它们都存在。所以你需要把它们放在一个数组中。

UPDATE
  areas
SET
  active = True
WHERE
  id = ANY(
    SELECT
      UNNEST(ARRAY[id, parent1, parent2, parent3, parent4])
    FROM
      areas
    WHERE
      id = 1000
  )