排序 MySQL 查詢中部分值類似於“John_120 “中的數字
為此,你可以與 ORDER BY 一起使用 SUBSTRING_INDEX()。我們先建立一個表 -
mysql> create table DemoTable1502 -> ( -> StudentId varchar(40) -> ); Query OK, 0 rows affected (0.54 sec)
使用 insert 命令在表中插入一些記錄 -
mysql> insert into DemoTable1502 values('John_120');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1502 values('John_201');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1502 values('Mike_178');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1502 values('Bob_198');
Query OK, 1 row affected (0.36 sec)使用 select 語句顯示錶中的所有記錄 -
mysql> select * from DemoTable1502;
這將會產生以下輸出 -
+-----------+ | StudentId | +-----------+ | John_120 | | John_201 | | Mike_178 | | Bob_198 | +-----------+ 4 rows in set (0.00 sec)
以下是按列部分值排序的查詢 -
mysql> select substring_index(StudentId,'_',1) as LeftPart, -> substring_index(StudentId,'_',-1) as RightPart -> from DemoTable1502 -> order by RightPart;
這將會產生以下輸出 -
+----------+-----------+ | LeftPart | RightPart | +----------+-----------+ | John | 120 | | Mike | 178 | | Bob | 198 | | John | 201 | +----------+-----------+ 4 rows in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP