Getting all parent rows in one SQL query

后端 未结 7 1985
温柔的废话
温柔的废话 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:31

    In addition to the above solutions:

    post
    -----
    id
    title
    author
    
    author
    ------
    id
    parent_id
    name
    
    
    [post]
    
    id  | title | author |  
    ----------------------
    1   | abc   | 3      |
    
    
    [author]
    
    | id    | parent_id | name  |   
    |---------------------------|
    | 1     | 0         | u1    |
    | 2     | 1         | u2    |
    | 3     | 2         | u3    |
    | 4     | 0         | u4    |
    

    an author including parents can have an access to the post.

    I want to check whether author has an access to the post.

    Solution:

    give the post author's id and return all its authors and author's parents

    SELECT T2.id, T2.username 
    FROM (
        SELECT @r AS _id, 
            (SELECT @r := parent_id FROM users WHERE id = _id) AS parent_id,
            @l := @l + 1
        FROM
            (SELECT @r := 2, @l := 0) vars, 
            users h     
        WHERE @r <> 0) T1 JOIN users T2 
    ON T1._id = T2.id;
    

    @r := 2 => assigning value to @r variable.

提交回复
热议问题