Number sorting problem in Mysql

When building a table by yourself, create a field type as varchar(2), but in fact it should be built as int(2). Because I'm only allowed to output numbers. This is nothing in the first place, it is nothing more than taking up some space, and I am too lazy to change it. But today I found a problem with sorting in the background. So, there is no way to change it. Let's briefly talk about MySQL's varchar sorting problem, and take it as a warning.
Next, I will sort by server_id from 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 result I want should be something like 10,8,7,6,5. But this 10 ranks behind the 2. Arranged by string. In fact, I want to use it as a numerical row.
Manual conversion type:
use the following method to sort after server_id+0, the problem is solved.
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 MySQL function CAST/CONVERT:
MySQL provides us with two type conversion functions: CAST and CONVERT, how can we let go of ready-made things?
The CAST() and CONVERT() functions can be used to get a value of one type and produce a value 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;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325383241&siteId=291194637