我有一行包含两个数字 Ant 字符串。我想对其进行排序,以便数字将按数字排序,并且所有字符串都将转到表的末尾。
ORDER BY (
CASE
WHEN `{$table}`.`{$row}` LIKE '%[^0-9]%'
THEN CAST(`{$table}`.`{$row}` AS DECIMAL)
ELSE `{$table}`.`{$row}`
END
) ASC"
但是数字仍然像字符串一样排序。
Results:
0
410
680
72
Some other string
Some string
It should be:
0
72
410
680
Some other string
Some string
最佳答案
试试这个:
order by (case when left(`{$table}`.`{$row}`, 1) between '0' and '9' then 0 else 1 end),
`{$table}`.`{$row}` + 0,
`{$table}`.`{$row}`
第一个表达式将数字放在前面(或至少以数字开头的字符串)。第二个是 MySQL 的一个很好的功能,它可以简单地将字符串转换为数字。第三个对非数字字符串进行排序。
编辑:
要仅包含数字(而不是前导数字),请先行:
order by (case when left(`{$table}`.`{$row}`, 1) REGEXP '^-?[0-9]+$' then 0 else 1 end),
`{$table}`.`{$row}` + 0,
`{$table}`.`{$row}`
关于mysql - SQL 将 varchar 排序为小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21759851/