MySQL ORDER BY字符串作为数字(较大数字以上的较大数字)

时间:2015-03-27 12:08:10

标签: mysql innodb

考虑code类型为VARCHAR的以下结果:

SELECT code
FROM lock
ORDER BY CAST(code AS signed) > 0 DESC, `code

|code|
|4   |  
|420 |
|5   |
|T6  |
|X30 |

如何更改查询以便按此顺序返回结果:

|code|
|4   |  
|5   |
|420 |
|T6  |
|X30 |

3 个答案:

答案 0 :(得分:5)

SELECT code
FROM lock
ORDER BY CAST(code AS signed) > 0 DESC, CAST(code AS signed) ASC, code ASC

第一个订单会将数字排序到前面。第二个订单只会对数字进行排序,而第一个订单会将它们保持在开头。第三个只对字符串进行排序,数字将保持其顺序,因为它们已经排序。

答案 1 :(得分:0)

E.g:

SELECT *
     , code+0 
     , code+0=0
  FROM (SELECT '4' code UNION 
        SELECT '420'    UNION 
        SELECT '5'      UNION 
        SELECT 'T6'     UNION 
        SELECT 'X30') n 
 ORDER 
    BY code+0=0
     , code+0
     , code;

+------+--------+----------+
| code | code+0 | code+0=0 |
+------+--------+----------+
| 4    |      4 |        0 |
| 5    |      5 |        0 |
| 420  |    420 |        0 |
| T6   |      0 |        1 |
| X30  |      0 |        1 |
+------+--------+----------+

答案 2 :(得分:-1)

SQL中的

LENGTH()函数用于获取字符串的长度:

SELECT code
FROM lock
ORDER BY LENGTH(code), code

<强> OUT:

+------+
| code |
+------+
| 4    |
| 5    |
| T6   |
| 420  |
| X30  |
+------+