简体   繁体   English

SQL命令varchar作为小数

[英]SQL order varchar as decimals

I have a row that has both numbers ant strings. 我有一排同时包含两个数字的蚂蚁字符串。 I whant to order it so that numbers will be ordered as numbers and all the strings would go to the end of table. 我希望对它进行排序,以便将数字作为数字进行排序,并且所有字符串都将到达表的末尾。

ORDER BY (
          CASE 
               WHEN `{$table}`.`{$row}` LIKE '%[^0-9]%' 
                    THEN CAST(`{$table}`.`{$row}` AS DECIMAL) 
               ELSE `{$table}`.`{$row}` 
          END
         ) ASC"

But instead the numbers are still sorted like strings. 但是,数字仍然像字符串一样排序。

Results: 
0
410
680
72
Some other string
Some string


It should be:
0
72
410
680
Some other string
Some string

Try this: 尝试这个:

order by (case when left(`{$table}`.`{$row}`, 1) between '0' and '9' then 0 else 1 end),
         `{$table}`.`{$row}` + 0,
         `{$table}`.`{$row}`

The first expression puts numbers first (or at least strings that start with a number). 第一个表达式将数字放在第一位(或至少以数字开头的字符串)。 The second is a nice MySQL feature that simply converts a string to a number. 第二个是很好的MySQL功能,它可以简单地将字符串转换为数字。 The third sorts the non-numeric strings. 第三种对非数字字符串进行排序。

EDIT: 编辑:

To have only numbers (instead of leading numbers) go first: 要仅具有数字(而不是前导数字),请先执行以下操作:

order by (case when left(`{$table}`.`{$row}`, 1) REGEXP '^-?[0-9]+$' then 0 else 1 end),
         `{$table}`.`{$row}` + 0,
         `{$table}`.`{$row}`

How about the following ( SQL Fiddle ): 怎么样( SQL小提琴 ):

SELECT * FROM 
(
  SELECT field1
  FROM MyTable
  WHERE field1 REGEXP '^-?[0-9]+$'
  ORDER BY CAST(field1 AS DECIMAL)
  )AS m
UNION
SELECT * FROM 
(
  SELECT field1
  FROM MyTable
  WHERE field1 NOT REGEXP '^-?[0-9]+$'
  ORDER BY field1
) AS mm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM