由于id的字段类型为varchar类型,导致在根据id排序时出现问题
下面是我在MySQL数据库中以uniqueid排序,排序后的结果如下:
MariaDB [da]> select uniqueid,username from user order by uniqueid limit 15;
+----------+----------+
| uniqueid | username |
+----------+----------+
| 1 | yt |
| 10 | ai28 |
| 11 | ai29 |
| 12 | ai30 |
| 13 | ai31 |
| 14 | ai32 |
| 15 | ai33 |
| 16 | ai34 |
| 17 | ai35 |
| 18 | ai36 |
| 19 | ai37 |
| 2 | ai20 |
| 20 | ai38 |
| 21 | ai39 |
| 22 | ai40 |
+----------+----------+
15 rows in set (0.00 sec)
MariaDB [da]>
很明显是不正确的,理论上是应该按照数值排序,但却是以字符串排序的。
手动转换类型:
使用id+0然后再排序就可以解决
MariaDB [da]> select uniqueid,username from user order by uniqueid+0 limit 15;
+----------+----------+
| uniqueid | username |
+----------+----------+
| 1 | yt |
| 2 | ai20 |
| 3 | ai21 |
| 4 | ai22 |
| 5 | ai23 |
| 6 | ai24 |
| 7 | ai25 |
| 8 | ai26 |
| 9 | ai27 |
| 10 | ai28 |
| 11 | ai29 |
| 12 | ai30 |
| 13 | ai31 |
| 14 | ai32 |
| 15 | ai33 |
+----------+----------+
15 rows in set (0.00 sec)
MariaDB [da]>
注:
mysql 查看表结构(字段类型)
desc 表名;
show columns from 表名;
describe 表名;
mysql 查看创建表sql
show create table 表名;
mysql排序
SQL SELECT 语句使用 ORDER BY 子句将查询数据排序后再返回数据:
SELECT field1, field2,...fieldN FROM table_name1, table_name2...
ORDER BY field1 [ASC [DESC][默认 ASC]], [field2...] [ASC [DESC][默认 ASC]]
- 你可以使用任何字段来作为排序的条件,从而返回排序后的查询结果。
- 你可以设定多个字段来排序。
- 你可以使用 ASC 或 DESC 关键字来设置查询结果是按升序或降序排列。 默认情况下,它是按升序排列。
- 你可以添加 WHERE...LIKE 子句来设置条件。