[英]mysql need to get custom order of result
Have MySQL table like id
, parent_id
, order_nr
有像id
, parent_id
, order_nr
这样的MySQL表
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: 假设parent_id
和order_nr
是varchar列,但是您想将它们按数字排序,那么可以在订购时order_nr
这些列:
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) 假设ID为两位数(但可以扩展为任意位数)
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 或者id是字符串
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 2400 2300 2227 2226 2225 2200
When the parent_id
is 0 then just use the id
otherwise use the parent_id
; 当parent_id
为0时,只需使用id
否则使用parent_id
; sorting by order_nr
then breaks ties. 然后按order_nr
排序打破order_nr
。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.