如何在 MySQL 中對字母數字欄位進行排序?


若要對帶有“100X”、“2Z”等值的字母數字欄位進行排序,請使用 ORDER BY。我們首先建立一個表 −

mysql> create table DemoTable
-> (
-> StudentId varchar(100)
-> );
Query OK, 0 rows affected (0.52 sec)

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

mysql> insert into DemoTable values('2X');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable values('100Y');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('100X');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values('2Z');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('2Y');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable values('100Z');
Query OK, 1 row affected (0.17 sec)

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

mysql> select *from DemoTable;

輸出

這會產生以下輸出 −

+-----------+
| StudentId |
+-----------+
| 2X        |
| 100Y      |
| 100X      |
| 2Z        |
| 2Y        |
| 100Z      |
+-----------+
6 rows in set (0.00 sec)

以下是使用 MySQL 對字母數字欄位進行排序的查詢 −

mysql>select *from DemoTable order by (StudentId+0), right(StudentId, 1);

輸出

這會產生以下輸出 −

+-----------+
| StudentId |
+-----------+
| 2X        |
| 2Y        |
| 2Z        |
| 100X      |
| 100Y      |
| 100Z      |
+-----------+
6 rows in set, 6 warnings (0.00 sec)

更新日期: 30-06-2020

1K+ 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始學習
廣告