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

人盡茶涼 提交于 2019-12-07 14:56:10

问题


This is the table

  user_id | parent_id | lft
  --------|-----------|-----
        1 |           | 0
        2 |         1 | 0
        3 |         1 | 0
        4 |         2 | 0

Here is a query to do a CTE from node 1 and traverse all the children of user_id 1 until a leaf is reached and update the value of the travesed chidren lft field to 1

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

I am just asking for a query that will go in the opposite direction .. ie. from any node to the root node so I can update the value of lft


回答1:


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.


来源:https://stackoverflow.com/questions/19386334/postgres-recursive-query-to-update-values-of-a-field-while-traversing-parent-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!