简体   繁体   English

Postgres:将更新查询合并到层级表上的一个查询

[英]Postgres: Combine update queries to one query on hierarchic table

i have a hierarchic table where each row contains an id of various parents. 我有一个层次结构表,其中每一行都包含各种父母的ID。 updating a row (set it as active) means that i have to update every parent of this row. 更新一行(将其设置为活动状态)意味着我必须更新该行的每个父级。 how can i combine these queries into one query? 如何将这些查询合并为一个查询? currently i use this solution which is not very nice. 目前,我使用的解决方案不是很好。 i guess this can be done with a recursive CTE, but i can't figure out the right way here. 我想这可以通过递归CTE来完成,但是我在这里找不到正确的方法。 thanks in advance! 提前致谢!

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);

Basically you're saying set active = true if it's either the node itself, parent1, parent2, parent3 or parent4, which are all present when you query the node by id. 基本上,您说的是set active = true,如果它是节点本身,parent1,parent2,parent3或parent4,则在通过id查询节点时都存在。 So putting them together in an array is all you need. 因此,只需要将它们组合在一起。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM