Sql question: Getting Parent rows followed by child rows

前端 未结 3 1256
逝去的感伤
逝去的感伤 2021-01-24 10:57

id parent_id

1 0

2 0

3 2

4 0

5 1

6 0

I need a query that will return parent rows (parent_id=0) f

3条回答
  •  感情败类
    2021-01-24 11:25

    Here is an example solution using a union with an order by clause (It wont work for deep nesting though).

    SELECT  p.id, 
            p.parent_id, 
            p.name,  
            p.id AS sequence
    FROM topics AS p 
    WHERE p.parent_id = 0
    UNION 
    SELECT  t.id, 
            t.parent_id, 
            t.name, 
            t.parent_id AS sequence
    FROM topics AS t
    WHERE t.parent_id <> 0
    ORDER BY sequence, parent_id, name
    

提交回复
热议问题