简体   繁体   English

SQL,带小数点输入的varchar字段= ORDER BY未正确排序

[英]SQL, varchar field with decimals entries = ORDER BY not sorting proprely

So i have a table with a VARCHAR field. 所以我有一个带有VARCHAR字段的表。 It is used to sort a lot of decimals value: 它用于对很多小数值进行排序:

Let's say i have the following entries in my VARCHAR field: 假设我在VARCHAR字段中有以下条目:

  • 9.99 9.99
  • 263.28 263.28
  • 9.98 9.98

Let's say I want to display all entries using ORDER BY varchar DESC. 假设我要使用ORDER BY varchar DESC显示所有条目。 The result would be: 结果将是:

  • 9.99 9.99
  • 9.98 9.98
  • 263.28 263.28

When obviously 263.28 should be the first one. 显然, 263.28应该是第一个。 What's wrong ? 怎么了 ?

If you have all decimal values in varchar field then just convert it to decimal and then apply order by clause. 如果varchar字段中具有所有十进制值,则只需将其转换为十进制,然后应用order by子句即可。 I have not much idea about mysql data type and convert function, but in MS SQL you can convert it to decimal like 我对mysql数据类型和转换函数没有太多了解,但是在MS SQL中,您可以将其转换为十进制,例如

ORDER BY CAST(field AS DECIMAL(18,2)) DESC

UPDATE : 更新:

Yes, in MySQL also there is cast function : http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html 是的,在MySQL中也有强制转换功能: http : //dev.mysql.com/doc/refman/5.0/en/cast-functions.html

If you order by a varchar column, mysql will sort alphabetically. 如果按varchar列排序,则mysql将按字母顺序排序。 The first character "2" comes before "9". 第一个字符“ 2”在“ 9”之前。 That's why you get the order you see. 这就是为什么您得到订单的原因。 Cast the varchar column to decimal in the order by clause and it should work as you expect. 在order by子句中将varchar列强制转换为十进制,并且应该可以按预期工作。

Alternatively, you could update "9.99" to "009.99" and so on so that all the rows have the same number of characters. 或者,您可以将“ 9.99”更新为“ 009.99”,以此类推,以便所有行都具有相同数量的字符。 Then the alphabetical sort will match the numerical sort. 然后,字母排序将与数字排序匹配。 I'm not suggesting you actually use that as a solution - it just shows you how things work in the database. 我并不是建议您实际使用它作为解决方案-它只是向您显示事物在数据库中的工作方式。

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

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