在 MySQL 中将多条文本记录合并为一条
mysqlmysqli database
要合并多条文本记录,请使用 GROUP_CONCAT()。我们首先创建一个表 −
mysql> create table DemoTable1611 -> ( -> Value text -> ); Query OK, 0 rows affected (0.86 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1611 values('John'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1611 values('is'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1611 values('learning'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1611 values('Java'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1611 values('with'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable1611 values('MySQL Database'); Query OK, 1 row affected (0.12 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1611;
这将产生以下输出 −
+----------------+ | Value | +----------------+ | John | | is | | learning | | Java | | with | | MySQL Database | +----------------+ 6 rows in set (0.00 sec)
以下是合并多个文本记录的查询 −
mysql> select group_concat(Value separator ' ') from DemoTable1611;
这将产生以下输出 −
+-------------------------------------------+ | group_concat(Value separator ' ') | +-------------------------------------------+ | John is learning Java with MySQL Database | +-------------------------------------------+ 1 row in set (0.00 sec)