从 MySQL 中提取数据以使其格式化为重复值的最有效方法是什么

mysqlmysqli database更新于 2024/2/4 2:42:00

为此,您可以使用 GROUP_CONCAT()。让我们首先创建一个表 −

mysql> create table DemoTable1561
   -> (
   -> StudentName varchar(20),
   -> Title text
   -> );
Query OK, 0 rows affected (0.60 sec)

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

mysql> insert into DemoTable1561 values('Adam','Learning Java');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1561 values('Bob','Learning C');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1561 values('Adam','Learning Spring and Hibernate Framework');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable1561 values('Carol','Learning MySQL from basic');
Query OK, 1 row affected (0.30 sec)

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

mysql> select * from DemoTable1561;

这将产生以下输出 −

+-------------+-----------------------------------------+
| StudentName | Title                                   |
+-------------+-----------------------------------------+
| Adam        | Learning Java                           |
| Bob         | Learning C                              |
| Adam        | Learning Spring and Hibernare Framework |
| Carol       | Learning MySQL from basic               |
+-------------+-----------------------------------------+
4 rows in set (0.00 sec)

这是从 MySQL 中提取数据以便格式化的查询 −

mysql> select StudentName,group_concat(Title separator ',') as FormattedOutput from DemoTable1561
   -> group by StudentName;

这将产生以下输出 −

+-------------+-------------------------------------------------------+
| StudentName | FormattedOutput                                       |
+-------------+-------------------------------------------------------+
| Adam        | Learning Java,Learning Spring and Hibernate Framework |
| Bob         | Learning C                                            |
| Carol       | Learning MySQL from basic                             |
+-------------+-------------------------------------------------------+
3 rows in set (0.00 sec)

相关文章