如何按指定字符串在 MySQL 中排序?
我们首先创建一个表 −
mysql> create table DemoTable -> ( -> FirstName varchar(100) -> ); Query OK, 0 rows affected (0.53 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('Adam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('Johnny'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('Joy'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Jace'); Query OK, 1 row affected (0.20 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
这将产生以下输出 −
+-----------+ | FirstName | +-----------+ | John | | Adam | | Sam | | Johnny | | Joy | | Jace | +-----------+ 6 rows in set (0.00 sec)
以下是对指定字符串进行排序的查询。假设你需要首先对子字符串“Jo”进行排序 −
mysql> select *from DemoTable -> order by case when substring(FirstName, 1, 2) = 'Jo' then 0 else 1 end;
输出
这将产生以下输出 −
+-----------+ | FirstName | +-----------+ | John | | Johnny | | Joy | | Adam | | Sam | | Jace | +-----------+ 6 rows in set (0.00 sec)
广告