mySQL CAST and ASC / DESC

二次信任 提交于 2019-12-25 04:19:54

问题


I have a mysql_query

SELECT * FROM table ORDER BY CAST(row AS DECIMAL)

and want to change the sort direction. I tried ASC and DESC but both return exactly the same sort direction.

How do I resort it?

Thanks, greets

Julian


回答1:


That should work. Have you tried to display that, what your CAST(row AS DECIMAL) produces?

Paste example of data that you trying to sort. Maybe you have nulls there or numbers that cant fit into decimal type.

What version of mysql you are using? Maybe reason is this (from mysql help):

The change of storage format also means that DECIMAL columns no longer support the nonstandard extension that permitted values larger than the range implied by the column definition.




回答2:


I believe you could do your casting in the SELECT, and ORDER BY that new column. Downside is of course you would get 1 extra column in your response, but if that extra column doesn't affect anything then all's well.

SELECT *, CAST(row AS DECIMAL(5,2)) AS tempCol FROM table ORDER BY tempCol

Also, your DECIMAL should ideally specify its precision. =)

More details at http://dev.mysql.com/doc/refman/5.0/en/fixed-point-types.html




回答3:


If your row column has only one _ character inside, with the part before being alphabetic and the part after being numeric, this will work:

SELECT 
      *
    , SUBSTRING_INDEX(row, '_', 1) AS  FirstPart
    , CAST(SUBSTRING_INDEX(row, '_', -1) AS UNSIGNED) AS SecondPart
FROM 
      TableX
ORDER BY
      FirstPart
    , SecondPart 


来源:https://stackoverflow.com/questions/9352279/mysql-cast-and-asc-desc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!