将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;
阅读更多:MySQL 教程
结果如下
+----+-------+-------+
| 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)