在sqlite中递归地将自己的列连接到父列

Concat own column to parent column recursively in sqlite

我的目标是根据每条记录的位置创建一个唯一的 ID。下面是我的来源 table、预期输出和我已经尝试过的结果。

这是我的来源table。

ID Location Name ParentID
1 1 Room 1 NULL
2 1 Table 1 1
3 2 Table 2 1
4 1 Chair 1 2
5 2 Chair 2 2
6 9 Room 2 NULL
7 1 Chair 3 3

我的目标是得到这样的输出:

ID Location Name ParentID ConcatLocation
1 1 Room 1 NULL 1
2 1 Table 1 1 11
3 2 Table 2 1 12
4 1 Chair 1 2 111
5 2 Chair 2 2 112
6 9 Room 2 NULL 9
7 1 Chair 3 3 121

我试过 https://kimsereylam.com/sqlite/2020/03/13/recursive-query-in-sqlite-with-cte.html 但这并没有给我想要的结果。这是我从该网站制作的代码:

with recursive
    child_record(ID, Name, ParentID, Location, NewLocation) as (
        select S.ID, S.Name, S.ParentID, S.Location, S.Location
        from Source S
        
        UNION
        
        select S.ID, S.Name, S.ParentID, S.Location, S.Location, c.Location || S.Location
        from Source S, child_record c
        where c.ID = S.ParentID
    )
select * from child_record

但是 returns 我 table 有最初的 7 条记录,后面跟着 5 条记录,这些记录只连接了它们的第一个父级,而不是转到 ParentID NULL 的父级。

ID Location Name ParentID NewLocation
1 1 Room 1 NULL 1
2 1 Table 1 1 1
3 2 Table 2 1 2
4 1 Chair 1 2 1
5 2 Chair 2 2 2
6 9 Room 2 NULL 9
7 1 Table 3 6 1
2 1 Table 1 1 11
3 2 Table 2 1 12
4 1 Chair 1 2 11
5 2 Chair 2 2 12
7 1 Chair 3 3 21

NULL 作为 ParentID 的行开始,然后加入子项:

WITH cte(ID, Name, ParentID, Location, ConcatLocation) AS (
  SELECT ID, Location, Name, ParentID, Location
  FROM Source 
  WHERE ParentID IS NULL
  UNION ALL
  SELECT S.ID, S.Location, S.Name, S.ParentID, c.ConcatLocation || S.Location
  FROM Source S INNER JOIN cte c
  ON c.ID = S.ParentID
)
SELECT * FROM cte
ORDER BY ID

参见demo
结果:

ID Location Name ParentID ConcatLocation
1 1 Room 1 null 1
2 1 Table 1 1 11
3 2 Table 2 1 12
4 1 Chair 1 2 111
5 2 Chair 2 2 112
6 9 Room 2 null 9
7 1 Chair 3 3 121