11
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 排序(忽略*)并给出名称和值。

4

1 回答 1

28

MySQL 不允许您使用CAST('01' AS INT). 相反,它期望 a SIGNEDor UNSIGNED

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

查看MySQL 文档以CAST()获取完整的详细信息。

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

要强制最后对非数字字符串进行排序,您需要在其中应用 aCASE来为ORDER BY它们分配一个高得离谱的值。条件应该测试 in 的值01不等于0并且当转换为 aSIGNED时结果不是0,因为非数字字符串将转换为零。

如果不满足这些条件,则假定字符串是非数字的,并在 中给出 999999999 的值ORDER BY,这会将它们推到末尾。他们随后由 订购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,
于 2013-02-05T13:52:11.190 回答