sql - Postgres : Combine update queries to one query on hierarchic table

标签 sql postgresql

我有一个分层表,其中每一行都包含不同 parent 的 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);

最佳答案

基本上,如果它是节点本身、parent1、parent2、parent3 或 parent4,当您通过 id 查询节点时,它们都存在,那么您说的是 set active = true。因此,只需将它们放在一个数组中即可。

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

关于sql - Postgres : Combine update queries to one query on hierarchic table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50176708/

相关文章:

mysql - Left Join 基于字段值

postgresql - 使用通配符在 postgresql 中搜索

function - Postgres 可以在部分索引 where 子句中使用函数吗?

sql - 如何获取由另一列分区的值的第一个实例?

java - 我应该如何发送 Postgis 几何数据? WKT 还是 WKB?

mysql - 插入另一个表中的所有用户

php - 需要更新 mysql 查询以选择预订酒店房间或任何东西的日期范围

Java 解析 Oracle 解释计划

mysql - 排名不按连载更新

java - 大对象不能在自动提交模式下使用