在 MySQL 中对混合有数字的字符串进行排序?

mysqlmysqli database

在某些情况下使用 ORDER BY。让我们创建一个表 −

mysql> create table demo18
−> (
−> value text
−> );
Query OK, 0 rows affected (1.18 sec)

使用 insert 命令向表中插入一些记录 −

mysql> insert into demo18 values('John Smith');
Query OK, 1 row affected (0.06 sec)

mysql> insert into demo18 values('2J John has 58');
Query OK, 1 row affected (0.17 sec)

mysql> insert into demo18 values('2J John has 9');
Query OK, 1 row affected (0.09 sec)

使用 select 语句显示表中的记录 −

mysql> select *from demo18;

这将产生以下输出 −

+----------------+
| value          |
+----------------+
| John Smith     |
| 2J John has 58 |
| 2J John has 9  |
+----------------+
3 rows in set (0.00 sec)

以下是排序查询 −

mysql> select *from demo18
−> order by regexp_replace(value, '[0&minus9]*$', ''),
−> length(value),
−> value;

这将产生以下输出 −

+----------------+
| value          |
+----------------+
| 2J John has 9  |
| 2J John has 58 |
| John Smith     |
+----------------+
3 rows in set (0.14 sec)

相关文章


有用资源