如何使用单个 MySQL 查询将行压缩到逗号分隔列表?
要将行压缩到逗号分隔列表,请使用 GROUP_CONCAT()。我们首先创建一个表 −
mysql> create table DemoTable ( Id int, Name varchar(40) ); Query OK, 0 rows affected (0.52 sec)
使用 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)
使用 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)
广告