MySQL varchar sorting in numerical order

Source: Internet
Author: User

When creating a table by yourself, create a field type as varchar (2). In fact, it should be set to int (2. Because I can only output numbers. There's nothing to do with this. It's nothing more than taking up some space. I'm too lazy to change it. However, I found a Sorting Problem in the background today. So there is no way to change it. The following describes the varchar Sorting Problem of MySQL.

Next, I will sort the order of server_id in the database. Let's take a look at the sorted results:

Select server_id from cardserver where game_id = 1 order
By server_id DESC limit 10; + ----------- +
| Server_id |
+ ----------- +
| 8 |
| 7 |
| 6 |
| 5 |
| 4 |
| 3 |
| 2 |
| 10 |
| 1 |
+ ----------- +

 

Obviously, the expected result is 10, 8, 7, 6, and 5. But this 10 is behind 2. Sort by string. In fact, I want to arrange it as a numerical value.

Manual Conversion Type:

You can use the following method to sort server_id + 0 and then solve the problem.

Select server_id from cardserver where game_id = 1 order
By server_id + 0 DESC limit 10;

+ ----------- +
| Server_id |
+ ----------- +
| 10 |
| 8 |
| 7 |
| 6 |
| 5 |
| 4 |
| 3 |
| 2 |
| 1 |
+ ----------- +

 

Use the MySQL function cast/convert:

MySQL provides two types of conversion functions: Cast and convert. How can we let go of the ready-made stuff?

Cast () and convert () functions can be used to obtain values of one type and generate values of another type.
This type can be one of the following values:
Binary [(n)]
Char [(n)]
Date
Datetime
Decimal
Signed [integer]
Time
Unsigned [integer]

So we can also use cast to solve the problem:

Select server_id from cardserver where game_id = 1 order
By cast (server_id as signed) DESC limit 10;

You can also use convert to solve this problem:

Select server_id from cardserver where game_id = 1 order
By convert (server_id, signed) DESC limit 10;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.