如何在MySQL中合并行?
要合并MySQL中的行,请使用GROUP_CONCAT()。
让我们首先创建一个表-
mysql> create table DemoTable734 ( Id int, Name varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable734 values(101,'John'); mysql> insert into DemoTable734 values(102,'John'); mysql> insert into DemoTable734 values(103,'Chris'); mysql> insert into DemoTable734 values(104,'Chris'); mysql> insert into DemoTable734 values(104,'Chris');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable734;
这将产生以下输出-
+------+-------+ | Id | Name | +------+-------+ | 101 | John | | 102 | John | | 103 | Chris | | 104 | Chris | | 104 | Chris | +------+-------+ 5 rows in set (0.00 sec)
以下是合并行的查询-
mysql> select Name,group_concat(Distinct Id SEPARATOR ',') from DemoTable734 group by Name;
这将产生以下输出-
+-------+-----------------------------------------+ | Name | group_concat(Distinct Id SEPARATOR ',') | +-------+-----------------------------------------+ | Chris | 103,104 | | John | 101,102 | +-------+-----------------------------------------+ 2 rows in set (0.04 sec)