針對包含數字的字串(如“456 John Smith”)的列值,按字母(非數字)排序 MySQL 順序


要按字母排序,請使用 ORDER BY SUBSTRING()。我們首先建立一個表 -

mysql> create table DemoTable
(
   Id varchar(100)
);
Query OK, 0 rows affected (0.65 sec)

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

mysql> insert into DemoTable values('456 John Smith');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('897 Adam Smith');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('1009 Bob Smith');
Query OK, 1 row affected (0.13 sec)

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

mysql> select *from DemoTable;

這會產生以下輸出 -

+----------------+
| Id             |
+----------------+
| 456 John Smith |
| 897 Adam Smith |
| 1009 Bob Smith |
+----------------+
3 rows in set (0.00 sec)

以下是按字母排序的查詢 -

mysql> select *from DemoTable order by SUBSTRING(Id,LOCATE(' ', Id));

這會產生以下輸出 -

+----------------+
| Id             |
+----------------+
| 897 Adam Smith |
| 1009 Bob Smith |
| 456 John Smith |
+----------------+
3 rows in set (0.05 sec)

更新於:2019-09-25

105 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告