SQL Varchar Order

时间:2011-10-09 00:26:58

标签: mysql sql sql-order-by

为什么我有像(ratings = varchar)这样的记录:

A - 100
B - 70
C - 30

然后:

SELECT * FROM `videos` ORDER BY `rating` DESC

给出:

A - 30
B - 70
C - 100

SELECT * FROM `videos` ORDER BY `rating` ASC

给出:

A - 100
B - 70
C - 30

但是当(ratings = tinyint):

SELECT * FROM `videos` ORDER BY `rating` DESC

给出:

A - 100
B - 70
C - 30

2 个答案:

答案 0 :(得分:2)

当你有一个varchar列时,文本数据的长度和char'0'在char'1'之前(而不是在char'9'之后)的事实会影响排序顺序。

e.g。比较

select '100' as col1 
union all 
select '70' as col1
order by col1 asc

select '100' as col1 
union all 
select '070' as col1
order by col1 asc

你可以通过适当地将所有字符串填充到相同的长度来解决这个问题。

答案 1 :(得分:0)

你可以尝试:

SELECT * FROM videos ORDER BY rating, videos DESC