简体   繁体   中英

Retrieve parent-child hierarchy from a self-referencing mysql table

I have a mysql table structured like this (removed other columns, not relevant to the question):

id          parent_id
----------- -----------
1           0          
2           0            
3           0          
4           3          
5           2
6           1
7           1          

A "parent" is a row that has parent_id = 0 .

I would like to know if there is a way to formulate the query so that MySQL outputs the rows with each children right after its parents?

The intended result would be

id          parent_id
----------- -----------
1           0          
6           1            
7           1          
2           0          
5           2          
3           0          
4           3          

Thank you for your time.

MySQL does not support recursive queries, so if a child can have childs there's no way to formulate such a query. Otherwise this query should return the rows in the order that you need:

SELECT * FROM tablename
ORDER BY
  CASE WHEN parent_id=0 THEN id ELSE parent_id END,
  id

Please see fiddle here . The trick is to order rows by id if it's a parent or by parent_id if it's a child, and then by id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM