操作的表:
select * from test_max_min;
+----+----------+-------------------+
| id | area | best_history_data |
+----+----------+-------------------+
| 1 | beijing | 33 |
| 2 | beijing | 22 |
| 3 | shanghai | 18 |
| 4 | shanghai | 2 |
| 5 | chengdu | 1 |
| 6 | chengdu | 2 |
| 7 | henan | 13 |
| 8 | henan | 12 |
+----+----------+-------------------+
其中,表结构如下:
desc test_max_min;
+-------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+-------------+------+-----+---------+-------+
| id | int(11) | NO | | 0 | |
| area | varchar(45) | NO | | NULL | |
| best_history_data | varchar(45) | YES | | NULL | |
+-------------------+-------------+------+-----+---------+-------+
期待:将best_history_data按照顺序排序
但是,直接执行select * from test_max_min order by best_history_data;获取到的结果如下:
+----+----------+-------------------+
| id | area | best_history_data |
+----+----------+-------------------+
| 5 | chengdu | 1 |
| 8 | henan | 12 |
| 7 | henan | 13 |
| 3 | shanghai | 18 |
| 4 | shanghai | 2 |
| 6 | chengdu | 2 |
| 2 | beijing | 22 |
| 1 | beijing | 33 |
+----+----------+-------------------+
可以看出,best_history_data的排序中2在18的后边,不符合我们的预期。。。原因是best_history_data是字符串类型的数字,字符串比较大小是逐位从高位到低位逐个比较,所以字符串类型的数字18<2
如何解决:使用+0即可
select * from test_max_min order by best_history_data+0;
+----+----------+-------------------+
| id | area | best_history_data |
+----+----------+-------------------+
| 5 | chengdu | 1 |
| 4 | shanghai | 2 |
| 6 | chengdu | 2 |
| 8 | henan | 12 |
| 7 | henan | 13 |
| 3 | shanghai | 18 |
| 2 | beijing | 22 |
| 1 | beijing | 33 |
+----+----------+-------------------+