排序 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)
广告