简体   繁体   中英

mysql need to get custom order of result

Have MySQL table like id , parent_id , order_nr

Now selecting everything like this

SELECT * FROM `table1` WHERE 1 ORDER BY `id` DESC

And getting result like

`id`, `parent_id`, `order_nr`
"27",   "23",       "3" 
"26",   "23",       "2" 
"25",   "23",       "1" 
"24",   "0",        "0" 
"23",   "0",        "0" 
"22",   "0",        "0" 

Need to get same result just in order like this:

`id`, `parent_id`, `order_nr`
"24",   "0",        "0" 
"23",   "0",        "0" 
"25",   "23",       "3" 
"26",   "23",       "2" 
"27",   "23",       "1"
"22",   "0",        "0" 

how about this one:

SELECT * FROM `table1` WHERE 1 ORDER BY order_nr,parent_id,id DESC

you can try to swap what column should be order first.

Assuming that parent_id and order_nr are varchar columns, but you want to sort them as numbers, then you can cast the columns when you order:

SELECT *
FROM table1
ORDER BY CAST(parent_id AS SIGNED),   -- no need for CAST if already numeric
         CAST(order_nr AS SIGNED)

Note: Your first desired output does not seem to have any evident logic behind, so I gave a solution for the second one.

SELECT * FROM `table1` WHERE 1 ORDER BY `parent_id`, `order_nr` ASC

Output would be like:

`id`, `parent_id`, `order_nr`
"24",   "0",        "0" 
"23",   "0",        "0" 
"22",   "0",        "0" 
"25",   "22",       "1" 
"26",   "22",       "2" 
"27",   "22",       "3" 

Assuming two digits numbers for ids (but can be extended to any number of digits)

SELECT IF(parent_id=0,id,parent_id)*100+IF(parent_id=0,0,id)),* FROM table ORDER BY 1 DESC

or if ids are strings

SELECT CONCAT(IF(parent_id='0',LPAD(id,2,'0'),LPAD(parent_id,2,'0')),IF(parent_id='0','00',LPAD(id,2,'0'))),* FROM table ORDER BY 1 DESC

This will give you a first column which is

2400 2300 2227 2226 2225 2200

When the parent_id is 0 then just use the id otherwise use the parent_id ; sorting by order_nr then breaks ties. All sorting is descending order:

SELECT id, parent_id, order_nr,
       id AS sort_order
  FROM table1
 WHERE parent_id = '0'
UNION
SELECT id, parent_id, order_nr,
       parent_id AS sort_order
  FROM table1
 WHERE parent_id <> '0'
 ORDER
    BY sort_order DESC, order_nr DESC;

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