为此,您可以使用CASE语句。要排序,请使用ORDER BY子句。让我们首先创建一个表-mysql> create table DemoTable
-> (
-> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ClientName varchar(20)
-> );
使用insert命令在表中插入一些记录。一些记录具有特定的最后一个字符串,例如-D等-mysql> insert into DemoTable(ClientName) values('Mike');
mysql> insert into DemoTable(ClientName) values('John');
mysql> insert into DemoTable(ClientName) values('John-D');
mysql> insert into DemoTable(ClientName) values('John-Smith');
mysql> insert into DemoTable(ClientName) values('Mike-Smith');
mysql> insert into DemoTable(ClientName) values('Mike-D');
使用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)