문제

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. 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):

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top