在 MySQL 中对某一列进行排序并忽略特定单词

mysqlmysqli database更新于 2025/5/27 11:24:17

首先我们创建一个表 −

mysql> create table DemoTable
   -> (
   -> Name text
   -> );
Query OK, 0 rows affected (1.31 sec)

使用 insert 命令在表中插入一些记录。这里我们插入了一个带有特定单词"name"的名称,我们需要忽略它 −

mysql> insert into DemoTable values('John 7');
Query OK, 1 row affected (0.65 sec)

mysql> insert into DemoTable values('John 6');
Query OK, 1 row affected (0.42 sec)

mysql> insert into DemoTable values('John 9');
Query OK, 1 row affected (0.33 sec)

mysql> insert into DemoTable values('name John 3');
Query OK, 1 row affected (0.24 sec)

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

mysql> select *from DemoTable;

输出

这将产生以下输出 −

+-------------+
| Name        |
+-------------+
| John 7      |
| John 6      |
| John 9      |
| name John 3 |
+-------------+
4 rows in set (0.00 sec)

以下是在对列进行排序时忽略特定单词的查询 −

mysql> select *from DemoTable ORDER BY TRIM(REPLACE(LOWER(Name), 'name ', ''));

输出

这将产生以下输出 −

+-------------+
| Name        |
+-------------+
| name John 3 |
| John 6      |
| John 7      |
| John 9      |
+-------------+
4 rows in set (0.00 sec)

相关文章


有用资源