使用 MySQL 中的字串和數字對 VARCHAR 記錄排序


為此,請使用 ORDER BY 子句。讓我們首先建立一個表 -

mysql> create table DemoTable
   -> (
   -> StudentCode varchar(20)
   -> );
Query OK, 0 rows affected (0.57 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable values('101J');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('100A');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('100B');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('101S');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('103M');
Query OK, 1 row affected (0.15 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select * from DemoTable;

這將產生以下輸出 -

+-------------+
| StudentCode |
+-------------+
| 101J        |
| 100A        |
| 100B        |
| 101S        |
| 103M        |
+-------------+
5 rows in set (0.00 sec)

以下是使用字串和數字對 VARCHAR 記錄排序的查詢 -

mysql> select * from DemoTable order by StudentCode+0,StudentCode;

這將產生以下輸出 -

+-------------+
| StudentCode |
+-------------+
| 100A        |
| 100B        |
| 101J        |
| 101S        |
| 103M        |
+-------------+
5 rows in set, 5 warnings (0.00 sec)

更新於: 26-Feb-2020

429 瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告