簡體   English   中英

SQL命令varchar作為小數

[英]SQL order varchar as decimals

我有一排同時包含兩個數字的螞蟻字符串。 我希望對它進行排序,以便將數字作為數字進行排序,並且所有字符串都將到達表的末尾。

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}`

怎么樣( 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