How to order 1,2,3 not 1, 10, 11, 12 in mySQL

前端 未结 6 1119
天涯浪人
天涯浪人 2020-12-29 02:22

The following code outputs in order of 1, 10, 11, 12 of id.

I want to make it 1,2,3,4...

Could anyone tell me what I should do please.

$Q = $         


        
相关标签:
6条回答
  • 2020-12-29 02:53

    Make sure that the column that holds 1,2,3,4 is INT type, if it is TEXT, you will not get numerical order, but what you describe 1, 10, 11, 2, 22, 23, 31, etc;

    And like others mentioned, use ORDER BY

    0 讨论(0)
  • 2020-12-29 02:56

    First, add an order by clause at the end:

    ORDER BY category_id
    

    If category_id is a string, then you must treat it like an integer. There are a few ways to do this. I usually add a zero. You can also cast it.

    ORDER BY category_id + 0
    
    0 讨论(0)
  • 2020-12-29 03:00

    As previously mentioned MySQL doesn't support alphanumeric sorting. One common trick to solve this is to first order by length:

    ORDER BY LENGTH(column_name), column_name
    

    As long as the non-numeric part of the value is the same length, this will sort 1 before 10, 10 before 100, etc.

    0 讨论(0)
  • 2020-12-29 03:00

    Order by only working for numerical values(int), not work for varchar, char

    Your category_id should numerical, otherwise you need to cast values to numerical.

    0 讨论(0)
  • 2020-12-29 03:03

    Well, you're not setting any ORDER BY clause.

    0 讨论(0)
  • 2020-12-29 03:11

    You can do an explicit cast by doing:

    ORDER BY CAST(category_id AS UNSIGNED INTEGER)
    

    But you should reconsider you database layout as a field containing only numeric values should also be of an numeric type..

    Best wishes, Fabian

    0 讨论(0)
提交回复
热议问题