1

次の列と行を持つ items という名前のこのテーブルがあります。

id   item_name   parentId
--------------------------
1    Item 1         0
2    Item 2         1
3    Item 3         2
4    Item 4         1
5    Item 5         2
6    Item 6         3
7    Item 7         6
8    Item 8         7

再帰 CTE によって行の親のレベルを測定できますが、パスを次の形式で取得する必要があります: 1.1.1, 1.2.1 ... これが私の現在のクエリです:

with recursive items_cache (lvl, id, item_name, parent_id) as (
    select 0 as lvl, id, item_name, parent_id
    from items
    where parent_id = 0
  union all
    select items_cache.lvl + 1, items.id, items.item_name, items.parent_id
    from items_cache    
    join items  on items_cache.id = items.parent_id
    order by items_cache.lvl+1 desc, items.id
)
select
    lvl,
    *
from items_cache

望ましい結果:

id   item_name   parentId   lvl       path_index
-------------------------------------------------
1    Item 1         0        0        1
2    Item 2         1        1        1.1
3    Item 3         2        2        1.1.1
6    Item 6         3        3        1.1.1.1
7    Item 7         6        4        1.1.1.1.1
8    Item 8         7        5        1.1.1.1.1.1
5    Item 5         2        2        1.1.2
4    Item 4         1        1        1.2
9    Item 9         0        0        2

SQLiteでそれを行うにはどうすればよいですか? Android が実行する SQLite のバージョンは 3.21 であるため、ウィンドウ関数はサポートされていません。

4

2 に答える 2