如何在 MySQL 中排列字母數字列?
要對字母數字列進行排序,請將 LIKE 運算子與 SUBSTRING() 結合使用。我們首先建立一個表格,-
mysql> create table DemoTable -> ( -> StudentId varchar(100) -> ); Query OK, 0 rows affected (1.54 sec)
使用 insert 命令在表中插入一些記錄,-
mysql> insert into DemoTable values('S/TU/100'); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values('S/TU/1000'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('S/TU/10'); Query OK, 1 row affected (0.47 sec)
使用 select 語句顯示錶中的所有記錄,-
mysql> select *from DemoTable;
輸出
這將生成以下輸出,-
+-----------+ | StudentId | +-----------+ | S/TU/100 | | S/TU/1000 | | S/TU/10 | +-----------+ 3 rows in set (0.00 sec)
以下是對 MySQL 中的字母數字列進行排序的查詢,-
mysql> select StudentId from DemoTable where StudentId LIKE 'S%' order by substring(StudentId,1,9), substring(StudentId,10)*1;
輸出
這將生成以下輸出,-
+-----------+ | StudentId | +-----------+ | S/TU/10 | | S/TU/100 | | S/TU/1000 | +-----------+ 3 rows in set (0.00 sec)
廣告