mysql order by 负数,ORDER BY分别为正数& MySQL语句中的负数

I have a MySQL table and would like to return the rows based on a column value in this order:

First ascending order if the column >=0

Then descending order if the column <0

E.g. 0,2,4,7,-2,-3,-5

解决方案

Can use SIGN to sort the positive numbers to the top, then take the absolute value with ABS to get the desired ASC/DESC.

SELECT * FROM theTable

ORDER BY SIGN(col) DESC, ABS(col)

EDIT

As Nahuel pointed out, the above will sort 0's to the middle between positive and negative. To instead group them with the positives, you can use a CASE instead (or, if your column is only integers, the slightly magical SIGN(col + 1))

SELECT * FROM theTable

ORDER BY

CASE WHEN col >= 0 THEN 1 ELSE 2 END,

ABS(col)

你可能感兴趣的:(mysql,order,by,负数)