在 MySQL 中将多行合并成一个逗号分隔列表?


要将多行合并成一个逗号分隔列表,请使用 GROUP_CONCAT() 方法。我们首先创建一个表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(30),
   Marks int
   );
Query OK, 0 rows affected (0.52 sec)

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

mysql> insert into DemoTable(Name,Marks) values('John',67);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable(Name,Marks) values('Carol',69);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(Name,Marks) values('Sam',69);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Marks) values('David',78);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable(Name,Marks) values('Chris',69);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Name,Marks) values('Bob',67);
Query OK, 1 row affected (0.17 sec)

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

mysql> select *from DemoTable;

输出

+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
| 1  | John  | 67    |
| 2  | Carol | 69    |
| 3  | Sam   | 69    |
| 4  | David | 78    |
| 5  | Chris | 69    |
| 6  | Bob   | 67    |
+----+-------+-------+
6 rows in set (0.00 sec)

以下是 MySQL 中将多行合并成一个逗号分隔列表的查询 −

mysql> SELECT Marks, GROUP_CONCAT(Name ORDER BY Name ASC SEPARATOR ', ')
   from DemoTable GROUP BY Marks;

输出

+-------+-----------------------------------------------------+
| Marks | GROUP_CONCAT(Name ORDER BY Name ASC SEPARATOR ', ') |
+-------+-----------------------------------------------------+
| 67    | Bob, John                                           |
| 69    | Carol, Chris, Sam                                   |
| 78    | David                                               |
+-------+-----------------------------------------------------+
3 rows in set (0.00 sec)

更新时间: 2019-07-30

3K+ 浏览

启动你的 职业生涯

完成课程获得认证

开始
广告