MySQL 中數字混合字串的按字母數字順序排序
假設你在一個表中有一個 VARCHAR 列,其值為字串,數字在右側。例如 -
John1023 Carol9871 David9098
現在,假設你要根據整個列右側的數字進行排序。為此,請使用 ORDER BY RIGHT。
讓我們首先建立一個表 -
mysql> create table DemoTable757 ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientId varchar(100) ); Query OK, 0 rows affected (0.53 sec)
使用 insert 命令在表中插入一些記錄 -
mysql> insert into DemoTable757(ClientId) values('John1023'); Query OK, 1 row affected (0.41 sec) mysql> insert into DemoTable757(ClientId) values('Carol9871'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable757(ClientId) values('David9098'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable757(ClientId) values('Adam9989'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable757(ClientId) values('Bob9789'); Query OK, 1 row affected (0.20 sec)
使用 select 語句從表中顯示所有記錄 -
mysql> select *from DemoTable757;
這將生成以下輸出 -
+----+-----------+ | Id | ClientId | +----+-----------+ | 1 | John1023 | | 2 | Carol9871 | | 3 | David9098 | | 4 | Adam9989 | | 5 | Bob9789 | +----+-----------+ 5 rows in set (0.00 sec)
以下是 MySQL 中按字母數字排序的查詢 -
mysql> select Id,ClientId from DemoTable757 order by right(ClientId,4);
這將生成以下輸出 -
+----+-----------+ | Id | ClientId | +----+-----------+ | 1 | John1023 | | 3 | David9098 | | 5 | Bob9789 | | 2 | Carol9871 | | 4 | Adam9989 | +----+-----------+ 5 rows in set (0.00 sec)
廣告