如何在 MySQL 中合并行?
要在 MySQL 中合并行,请使用 GROUP_CONCAT()。
我们首先创建一个表−
mysql> create table DemoTable734 ( Id int, Name varchar(100) ); Query OK, 0 rows affected (0.73 sec)
使用 insert 命令向表中插入一些记录−
mysql> insert into DemoTable734 values(101,'John'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable734 values(102,'John'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable734 values(103,'Chris'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable734 values(104,'Chris'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable734 values(104,'Chris'); Query OK, 1 row affected (0.13 sec)
使用 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)
广告