MySQL查询根据通用匹配ID将每一行中的所有值连接起来
让我们首先创建一个表-
mysql> create table DemoTable ( StudentId int, StudentFirstName varchar(100), StudentLastName varchar(100) );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values(1000,'Adam','Smith'); mysql> insert into DemoTable values(1000,'John','Doe'); mysql> insert into DemoTable values(1000,'David','Miller');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-----------+------------------+-----------------+ | StudentId | StudentFirstName | StudentLastName | +-----------+------------------+-----------------+ | 1000 | Adam | Smith | | 1000 | John | Doe | | 1000 | David | Miller | +-----------+------------------+-----------------+ 3 rows in set (0.00 sec)
以下是基于公共匹配ID将每行中的所有值连接起来的查询-
mysql> select StudentId,group_concat(StudentFirstName),group_concat(StudentLastName) from DemoTable group by StudentId;
这将产生以下输出-
+-----------+--------------------------------+-------------------------------+ | StudentId | group_concat(StudentFirstName) | group_concat(StudentLastName) | +-----------+--------------------------------+-------------------------------+ | 1000 | Adam,John,David | Smith,Doe,Miller | +-----------+--------------------------------+-------------------------------+ 1 row in set (0.00 sec)