问题
I write ...
ORDER BY column ASC
but my column is VARCHAR
and it sorts wrong like 1, 10, 2
, instead of 1, 2, 10
.
How can I do it to sort like 1, 2, 10
?
回答1:
order by
cast(column as float)
Notes:
- Assumed you only have numbers in the columns. No "fish" or "bicycle"
- empty strings CAST to zero
Edit: For MySQL. You can not cast to float
order by
cast(column as decimal(38,10))
回答2:
You can cast to int...
order by cast(column as int)
DEMO
DECLARE @q as table(
name varchar(50),
columnn varchar(10)
)
insert into @q
VALUES('one','1'),('one','10'),('one','20'),('one','3'),('one','2'),('one','20')
select * from @q order by cast (columnn as int) desc
prints
-------------------------------------------------- ----------
one 20
one 20
one 10
one 3
one 2
one 1
So, Daniel, yes, it works :)
UPDATE:
order by cast(column as decimal(20,6))
Will cast the column values to decimal numbers with 20 digits max and 6 decimal places. Adjust it to your actual requirements.
回答3:
i used this way multiply it with one the query is :
ORDER BY columnname * 1 ASC
Example: Table user have value with column value [varchar(20)]
.
Then you can query it:
SELECT * FROM user ORDER BY value * 1
After we multiply it MySQL will treat it like a number but this way is not recommended for a heavy load.
回答4:
Try this:
order by CAST(column as UNSIGNED)
来源:https://stackoverflow.com/questions/7786124/how-to-sort-varchar-numeric-columns-by-desc-or-asc