Getting all parent rows in one SQL query

后端 未结 7 1906
温柔的废话
温柔的废话 2020-11-27 11:59

I have a simple MySQL table thats contains a list of categories, level is determined by parent_id:

id  name    parent_id
---------------------------
1   Home         


        
相关标签:
7条回答
  • 2020-11-27 12:37

    If You have slug instead of id then simply run sub-query to find id of child category.
    Table - categories
    | id | parentId | slug |
    |-------------------------|
    | 1  |    0      |    u1    |
    | 2  |    1      |    u2    |
    | 3  |    2      |    u3    |
    | 4  |    0      |    u4    |

    SELECT T2.id, T2.slug
    FROM (
        SELECT
            @r AS _id,
            (SELECT @r := parentId FROM categories WHERE id = _id) AS parentId,
            @l := @l + 1 AS lvl
        FROM
            (SELECT @r := (SELECT id FROM categories WHERE slug = 'u3'), @l := 0) vars,
            categories h
        WHERE @r <> 0) T1
    JOIN categories T2
    ON T1._id = T2.id
    ORDER BY T1.lvl DESC
    
    0 讨论(0)
提交回复
热议问题