操做的表:spa
select * from test_max_min;排序
+----+----------+-------------------+字符串
| id | area | best_history_data |test
+----+----------+-------------------+select
| 1 | beijing | 33 |history
| 2 | beijing | 22 |co
| 3 | shanghai | 18 |字符
| 4 | shanghai | 2 |數字
| 5 | chengdu | 1 |data
| 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 |
+----+----------+-------------------+