MySQL 如何使用单个查询将行折叠成逗号分隔列表
使用GROUP_CONCAT()将行折叠为逗号分隔列表。让我们先创建一个表 –
mysql> create table DemoTable
(
Id int,
Name varchar(40)
);
Query OK, 0 rows affected (0.52 sec)
Mysql
使用insert命令在表中插入一些记录 –
mysql> insert into DemoTable values(100,'Chris Brown');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(101,'Adam Smith');
Query OK, 1 row affected (0.84 sec)
mysql> insert into DemoTable values(101,'John Doe');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(100,'David Miller');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(101,'Carol Taylor');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(103,'Bob Taylor');
Query OK, 1 row affected (0.20 sec)
Mysql
使用select语句显示表中的所有记录 –
mysql> select *from DemoTable;
Mysql
这将产生以下输出 –
+------+--------------+
| Id | Name |
+------+--------------+
| 100 | Chris Brown |
| 101 | Adam Smith |
| 101 | John Doe |
| 100 | David Miller|
| 101 | Carol Taylor|
| 103 | Bob Taylor |
+------+--------------+
6 rows in set (0.00 sec)
Mysql
以下是折叠行为逗号分隔列表的查询 –
mysql> select Id,group_concat(Name) from DemoTable group by Id;
Mysql
这将会产生以下输出 –
+------+----------------------------------+
| Id | group_concat(Name) |
+------+----------------------------------+
| 100 | Chris Brown,David Miller |
| 101 | Adam Smith,John Doe,Carol Taylor |
| 103 | Bob Taylor |
+------+----------------------------------+
3 rows in set (0.00 sec)
Mysql
阅读更多:MySQL 教程