开发者

Mysql select order by acts like a string, not a number

How do you order by number if your number can fall below and be bigger than 0?

Example Mysql table:

|Name|Karma|
 __________
|Me  | -8  |
|Bill|  5  |
|Tom |  2  |
|Saly|  0  |
|San.| -3  |

Example select query

$sql="SELECT ka开发者_如何学JAVArma FROM table ORDER BY karma DESC";

The result I get is this (separated by comma): 5,2,0,-8,-3. Shouldn't it be 5,2,0,-3,-8? I discovered somewhere in the internet that mysql orders by string. How to make it order by number?


Karma will be ordered as a string if you have made it a string, i.e. a varchar column.

Convert the column to a INT, and it will order numerically.

You also have the option of not changing the table, but casting the column into the right type while sorting:

SELECT karma FROM table ORDER BY CAST(karma AS int) DESC

but that is bad for performance.


There's another weirdest option:

SELECT karma FROM table ORDER BY karma+0 DESC
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜