MySQL 查询按某个最后字符串字符排序的方法?
为此,可以使用 CASE 语句。要排序,请使用 ORDER BY 子句。我们先创建一个表 -
mysql> create table DemoTable -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(20) -> ); Query OK, 0 rows affected (0.54 sec)
使用 insert 命令在表中插入一些记录。某些记录具有某些最后字符串,如 -D 等 -
mysql> insert into DemoTable(ClientName) values('Mike'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(ClientName) values('John'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(ClientName) values('John-D'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(ClientName) values('John-Smith'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(ClientName) values('Mike-Smith'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(ClientName) values('Mike-D'); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 1 | Mike | | 2 | John | | 3 | John-D | | 4 | John-Smith | | 5 | Mike-Smith | | 6 | Mike-D | +----------+------------+ 6 rows in set (0.00 sec)
以下是按某个最后字符串字符排序的查询 -
mysql> select -> case -> when right(ClientName,length(ClientName)-instr(ClientName,'-')) = `ClientName` THEN '' -> else right(`ClientName`,length(`ClientName`)-INSTR(`ClientName`,'-')) -> end as `last`, -> `ClientName` -> from -> DemoTable -> ORDER BY -> `last`,`ClientName`;
这将产生以下输出 -
+-------+------------+ | last | ClientName | +-------+------------+ | | John | | | Mike | | D | John-D | | D | Mike-D | | Smith | John-Smith | | Smith | Mike-Smith | +-------+------------+ 6 rows in set (0.00 sec)
广告