如何使用单个MySQL查询将行折叠为以逗号分隔的列表?
要将行折叠为逗号分隔的列表,请使用GROUP_CONCAT()。让我们首先创建一个表-
mysql> create table DemoTable ( Id int, Name varchar(40) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(100,'Chris Brown'); mysql> insert into DemoTable values(101,'Adam Smith'); mysql> insert into DemoTable values(101,'John Doe'); mysql> insert into DemoTable values(100,'David Miller'); mysql> insert into DemoTable values(101,'Carol Taylor'); mysql> insert into DemoTable values(103,'Bob Taylor');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+------+--------------+ | 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> select Id,group_concat(Name) from DemoTable group by Id;
这将产生以下输出-
+------+----------------------------------+ | 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)