我有一张桌子:
col1 | col2 | col3
-----+------+-------
1 | a | 5
5 | d | 3
3 | k | 7
6 | o | 2
2 | 0 | 8
Run Code Online (Sandbox Code Playgroud)
如果用户搜索"1",程序将查看col1具有"1"的程序,然后它将获得col3"5"中的值,然后程序将继续搜索"5",col1并且将获得"3" in col3等等.所以它会打印出来:
1 | a | 5
5 | d | 3
3 | k | 7
Run Code Online (Sandbox Code Playgroud)
如果用户搜索"6",它将打印出来:
6 | o | 2
2 | 0 | 8
Run Code Online (Sandbox Code Playgroud)
如何构建SELECT查询来做到这一点?
This is the table
user_id | parent_id | lft
--------|-----------|-----
1 | | 0
2 | 1 | 0
3 | 1 | 0
4 | 2 | 0
Run Code Online (Sandbox Code Playgroud)
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 …Run Code Online (Sandbox Code Playgroud)