对带有特殊字符(如"2321/78/54-6")的记录进行排序
mysqlmysqli database
要排序,请使用 ORDER BY SUBSTRING()。我们首先创建一个表 −
mysql> create table DemoTable -> ( -> Value varchar(40) -> ); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('2321/78/54-6') -> ; Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('2321/78/54-8'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2321/78/54-5'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('2321/78/54-9'); Query OK, 1 row affected (0.21 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable;
这将产生以下输出 −
+--------------+ | Value | +--------------+ | 2321/78/54-6 | | 2321/78/54-8 | | 2321/78/54-5 | | 2321/78/54-9 | +--------------+ 4 rows in set (0.00 sec)
这是对带有特殊字符的记录进行排序的查询 −
mysql> select * from DemoTable -> where Value like '2321/78/54%' -> order by substring(Value from 1 for 10),cast(substring(Value from 11) as decimal);
这将产生以下输出 −
+--------------+ | Value | +--------------+ | 2321/78/54-9 | | 2321/78/54-8 | | 2321/78/54-6 | | 2321/78/54-5 | +--------------+ 4 rows in set (0.05 sec)