要在一行中连接多行和多列,可以将GROUP_CONCAT()与一起使用CONCAT()
。让我们首先创建一个表-
mysql> create table DemoTable1463 -> ( -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ClientName varchar(20), -> ClientAge int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1463(ClientName,ClientAge) values('Adam Smith',34); mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Doe',29); mysql> insert into DemoTable1463(ClientName,ClientAge) values('David Miller',NULL); mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Smith',32);
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1463;
这将产生以下输出-
+----------+--------------+-----------+ | ClientId | ClientName | ClientAge | +----------+--------------+-----------+ | 1 | Adam Smith | 34 | | 2 | John Doe | 29 | | 3 | David Miller | NULL | | 4 | John Smith | 32 | +----------+--------------+-----------+ 4 rows in set (0.00 sec)
以下是在单个行中连接多个行和列的查询-
mysql> select group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) from DemoTable1463;
这将产生以下输出-
+------------------------------------------------------------------------+ | group_concat(concat(ClientId,':',ClientName,':',IFNULL(ClientAge,''))) | +------------------------------------------------------------------------+ | 1:Adam Smith:34,2:John Doe:29,3:David Miller:,4:John Smith:32 | +------------------------------------------------------------------------+ 1 row in set (0.04 sec)