简体   繁体   中英

How list child after parent in mysql query

i have data in mysql table like this

id ||  act  || parent || level
1  ||   13  ||  0     ||  1
2  ||   13  ||  0     ||  1 
3  ||   13  ||  1     ||  2
4  ||   13  ||  2     ||  2
5  ||   13  ||  1     ||  2

How to query in mysql, if i want the result like this :

id ||  act  || parent || level
1  ||   13  ||  0     ||  1
3  ||   13  ||  1     ||  2 
5  ||   13  ||  1     ||  2
2  ||   13  ||  0     ||  1
4  ||   13  ||  2     ||  2

Thank's before :)

The trick here would be to determine a custom sorting parameter. It parent value is 0, we can simply use that row's id value; else the parent value. This is because the parent value for other levels is same the row id for the parent.

We will also use multiple level Order By , with second level ordering done using id .

You can do something like this:

SELECT 
  id, 
  act, 
  parent, 
  level, 
  (CASE WHEN parent = 0 THEN id ELSE parent END) AS custom_sort_parameter 
FROM 
  your_table_name 
ORDER BY custom_sort_parameter, id 

I have done calculation of custom_sort_parameter in the Select clause, for code readability and ease to understand. But you can shift it to Order By clause instead (to avoid getting one more unnecessary column). It is exhibited in the Demo below.


Schema (MySQL v5.7)

Create table your_table_name 
(id int, act int, parent int, level int);

Insert into your_table_name 
VALUES (1,13,0,1), 
       (2,13,0,1), 
       (3,13,1,2), 
       (4,13,2,2), 
       (5,13,1,2);

Query #1

SELECT 
  id, 
  act, 
  parent, 
  level
FROM 
  your_table_name 
ORDER BY 
  CASE 
    WHEN parent = 0 THEN id 
    ELSE parent 
  END 
  , id;

| id  | act | parent | level |
| --- | --- | ------ | ----- |
| 1   | 13  | 0      | 1     |
| 3   | 13  | 1      | 2     |
| 5   | 13  | 1      | 2     |
| 2   | 13  | 0      | 1     |
| 4   | 13  | 2      | 2     |

View on DB Fiddle

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