MySQL order by (str to int)

那年仲夏 提交于 2019-12-18 07:56:59

问题


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

Column 01 has numeric values as varchar. I need to order top 3 of '01' as integer. Why doesn't this query working?

Table like this;

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

Query should order by 01 (dismiss *) and give names and values.


回答1:


MySQL doesn't permit you to CAST('01' AS INT). It expects instead a SIGNED or UNSIGNED.

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

Review the MySQL docs on CAST() for full details.

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

To force the non-numeric strings to be sorted last, you will need to apply a CASE in the ORDER BY which assigns them an absurdly high value. The condition should test that the value in 01 is not equal to 0, and when cast to a SIGNED the result is not 0, owing to the fact that non-numeric strings will cast to zero.

If those conditions are not met, the string is assumed to be non-numeric, and given a value of 999999999 in the ORDER BY, which pushes them to the end. They're subsequently ordered 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

To make these sort descending, use an absurdly low value (negative) instead of a high value

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


来源:https://stackoverflow.com/questions/14709058/mysql-order-by-str-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!