MySQL 查询如何按字符串字段中的数字字符对行进行分组?

mysqlmysqli database

为此,您可以借助 + 运算符将 0 与字符串字段连接起来。这里的场景就像我们需要从字符串字段"9844Bob"中获取数字"9844"。

首先我们创建一个表 −

mysql> create table DemoTable
(
   StudentId varchar(100)
);
Query OK, 0 rows affected (0.92 sec)

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

mysql> insert into DemoTable values('9844Bob');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('6375DavidMiller');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('007');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values('97474BobBrown');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('9844Bob56Taylor');
Query OK, 1 row affected (0.16 sec)

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

mysql> select *from DemoTable;

这将产生以下输出 −

+-----------------+
| StudentId       |
+-----------------+
| 9844Bob         |
| 6375DavidMiller |
| 007             |
| 97474BobBrown   |
| 9844Bob56Taylor |
+-----------------+
5 rows in set (0.00 sec)

以下是按字符串字段中的数字字符对行进行分组的查询 −

mysql> select StudentId,0+StudentId as GroupValue from DemoTable;

这将产生以下输出 −

+-----------------+------------+
| StudentId       | GroupValue |
+-----------------+------------+
| 9844Bob         |       9844 |
| 6375DavidMiller |       6375 |
| 007             |          7 |
| 97474BobBrown   |      97474 |
| 9844Bob56Taylor |       9844 |
+-----------------+------------+
5 rows in set, 4 warnings (0.00 sec)

相关文章