MySQL顺序(str到int)

时间:2013-02-05 13:48:59

标签: mysql sql-order-by

SELECT `01` FROM perf WHERE year = '2013' order by CAST(`01` AS INT) LIMIT 3

列01的数值为varchar。我需要将'01'的前3个整数排序。为什么这个查询不起作用?

这样的表;

+----------------------+
| name | 01 | 02 | year|
+----------------------+
|name1 | 90 |*** |2013 |
+----------------------+
|name2 | 93 | 55 |2013 |
+----------------------+
|name3 |*** | 78 |2013 |
+----------------------+

查询应按01排序(忽略 * )并提供名称和值。

1 个答案:

答案 0 :(得分:20)

MySQL不允许你CAST('01' AS INT)。它需要SIGNEDUNSIGNED

SELECT `01` FROM perf WHERE year = '2013' order by CAST(`01` AS SIGNED) LIMIT 3

查看MySQL docs on CAST()以获取完整详情。

mysql> SELECT CAST('01' AS SIGNED);
+----------------------+
| CAST('01' AS SIGNED) |
+----------------------+
|                    1 |
+----------------------+
1 row in set (0.00 sec)

要强制最后对非数字字符串进行排序,您需要在CASE中应用ORDER BY,这会为它们分配一个荒谬的高值。条件应该测试01中的值不等于0,当投放到SIGNED时,结果不是0,由于非数字字符串将被转换为零。

如果不满足这些条件,则假定该字符串为非数字,并在ORDER BY中给出值999999999,将其推送到最后。它们随后由name订购。

SELECT * FROM perf 
WHERE year = '2013'
ORDER BY
  CASE WHEN (`01` <> '0' AND CAST(`01` AS SIGNED) <> 0) THEN CAST(`01` AS SIGNED) ELSE 999999999 END,
  name
LIMIT 3

http://sqlfiddle.com/#!2/846e2/6

要使这些排序降序,请使用荒谬的低值(负值)而不是高值

  CASE WHEN (`01` <> '0' AND CAST(`01` AS SIGNED) <> 0) THEN CAST(`01` AS SIGNED) ELSE -999999999 END DESC,