针对包含数字的字符串(如“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 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.