问题
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:
- Starting set of records is determined by the first select in UNION ALL within WITH RECURSIVE clause.
- 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.
- 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