为什么MySQL中的排序不能正常工作?

时间:2015-06-30 09:17:00

标签: mysql sorting

我的表名为price,数据类型为varchar(25)。在查询中,我获取值45000,32000,420,237和180,并按ascending顺序对它们进行排序。它给我结果180,237,32000,420,45000,但我不知道为什么它按照前三位数进行排序,如果其中一个是三位数,如果所有数字都是4位数,那么它就是'工作正常。任何解决方案都将不胜感激。

我在Query中使用了CAST(prix as decimal)它仍然无效。

查询的某些部分和我使用prix case排序

WHEN (_flg_asc_desc = 0 AND _order_by_flg = 1) THEN CAST(a.prix as decimal)

见下文

ORDER BY
CASE 
    WHEN (CAST(a.prix as decimal) IS NULL 
    OR CAST(a.prix as decimal) = 'NA' 
    OR CAST(a.prix as decimal) = 'N/A' 
    OR CAST(a.prix as decimal) = '') THEN 1 ELSE 0 
END,
CASE 
    WHEN (CAST(a.surface as decimal) IS NULL 
    OR CAST(a.surface as decimal) = 'NA' 
    OR CAST(a.surface as decimal) = 'N/A' 
    OR CAST(a.surface as decimal) = '') THEN 1 ELSE 0 
END,
CASE 
    WHEN (_flg_asc_desc = 0 AND _order_by_flg = 0) THEN a.date_last_modif 
    WHEN (_flg_asc_desc = 0 AND _order_by_flg = 1) THEN CAST(a.prix as decimal) //   <==== My case in sorting prix
    WHEN (_flg_asc_desc = 0 AND _order_by_flg = 2) THEN CAST(a.surface as decimal) 
END ASC,

CASE 
    WHEN (_flg_asc_desc = 1 AND _order_by_flg = 0) THEN a.date_last_modif 
    WHEN (_flg_asc_desc = 1 AND _order_by_flg = 1) THEN CAST(a.prix as decimal) //   <==== My case in sorting prix
    WHEN (_flg_asc_desc = 1 AND _order_by_flg = 2) THEN CAST(a.surface as decimal) 
END DESC

1 个答案:

答案 0 :(得分:1)

因为数据是字符串(VARCHAR),所以数据库按字母顺序排序,而不是按数字排序。您必须在order by子句中强制转换为整数(DECIMAL)以允许数字排序。

如果您想了解更多详情,请发布一段代码,以便我们查看语法。