Get all data of parent child relation-ship from same table in mysql

前端 未结 1 736
太阳男子
太阳男子 2021-02-03 15:22

I am trying to get all rows which meets the parent child relation ship. for example

  id         Title    parent_id
  1200        A       1000
  1201        B            


        
相关标签:
1条回答
  • 2021-02-03 15:41

    if you're just looking for it's parent,grandparent,greatgrand parent you can use something like this.

    SELECT id,title,parent_id FROM
        (SELECT id,title,parent_id,
           CASE WHEN id = 1209 THEN @id := parent_id
                WHEN id = @id THEN @id := parent_id
                END as checkId
         FROM Test
         ORDER BY id DESC) as T
    WHERE checkId IS NOT NULL
    

    sqlfiddle

    And just in case if you wanted to find all children, and grand children or great grand children of an id you can use this

    SELECT id,title,parent_id FROM
        (SELECT id,title,parent_id,
                CASE WHEN id = 1200 THEN @idlist := CONCAT(id)
                     WHEN FIND_IN_SET(parent_id,@idlist) THEN @idlist := CONCAT(@idlist,',',id)
                END as checkId
         FROM Test
         ORDER BY id ASC) as T
    WHERE checkId IS NOT NULL
    

    sqlfiddle for finding children

    query for finding all parents/grandparents/greatgrandparents of multiple children

    SELECT id,title,parent_id FROM
    (SELECT id,title,parent_id,
           CASE WHEN id in (1209,1206) THEN @idlist := CONCAT(IFNULL(@idlist,''),',',parent_id)
                WHEN FIND_IN_SET(id,@idlist) THEN @idlist := CONCAT(@idlist,',',parent_id)
                END as checkId
    FROM Test
    ORDER BY id DESC)T
    WHERE checkId IS NOT NULL
    

    sqlfiddle

    0 讨论(0)
提交回复
热议问题