mysql 检索上层层次结构

nbnkbykc  于 2022-12-03  发布在  Mysql
关注(0)|答案(1)|浏览(118)

我将类别存储在单个表中。

id  name    parentId    path    
A1  Cat 1   0           Cat 1
A2  Cat 2   A1          Cat 1 > Cat 2
A3  Cat 3   A2          Cat 1 > Cat 2 > Cat 3
A4  Cat 4   A3          Cat 1 > Cat 2 > Cat 3 > Cat 4
A5  Cat 5   A4          Cat 1 > Cat 2 > Cat 3 > Cat 4 > Cat 5
A6  Cat 6   A5          Cat 1 > Cat 2 > Cat 3 > Cat 4 > Cat 5 > Cat 6

我想获取所有的上层结构,直到我达到父类别id。
到目前为止,我所取得的成就是:

with recursive cte (id, name, parentId, path) AS (
    select
        id,
        name,
        parentId,
        path
    from
        categories
    where
        parentId = 'A3'
    union
    all
    select
        c.id,
        c.name,
        c.parentId,
        c.path
    from
        categories c
        inner join cte on c.parentId = cte.id
)
select
    *
from
    cte;

现在,上面的查询的问题是,我给出了较低的层次结构:

id  name    parentId    path
A4  Cat 4   A3  Cat 1 > Cat 2 > Cat 3 > Cat 4
A5  Cat 5   A4  Cat 1 > Cat 2 > Cat 3 > Cat 4 > Cat 5
A6  Cat 6   A5  Cat 1 > Cat 2 > Cat 3 > Cat 4 > Cat 5 > Cat 6

但我期待的是:

id  name    parentId    path
A2  Cat 2   A1          Cat 1 > Cat 2
A1  Cat 1   0           Cat 1

我创建了一个可重现的场景:
https://dbfiddle.uk/D3czXMX4

flvlnr44

flvlnr441#

您只需要反转连接中关系的方向,从id开始而不是parentId -

with recursive cte (id, name, parentId, path) AS (
    select
        id,
        name,
        parentId,
        path
    from
        categories
    where
        id = 'A3'
    union
    all
    select
        c.id,
        c.name,
        c.parentId,
        c.path
    from
        categories c
        inner join cte on c.id = cte.parentId
)
select
    *
from
    cte;

db<>fiddle

相关问题