Postgres recursive query to update values of a field while traversing parent_id

你说的曾经没有我的故事 提交于 2019-12-06 01:11:19

The query which updates all nodes starting from some node and up to the root is very similar:

WITH RECURSIVE d AS (
  SELECT user_id
   FROM btrees
   WHERE user_id = :node_id
 UNION ALL
  SELECT c.user_id
   FROM d JOIN btrees c ON d.parent_id = c.user_id
)
UPDATE btrees b set lft = 1
 FROM d
 WHERE d.user_id = b.user_id

Note that condition in join is reversed.

In general recursive queries work as follows:

  1. Starting set of records is determined by the first select in UNION ALL within WITH RECURSIVE clause.
  2. The second select in UNION ALL defines how the next level records are derived from the records found so far. When traversing from top to bottom this query should find all children. When traversing from bottom to top this should find the parent.
  3. Step 2 is performed until no new records are added at some iteration.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!