使用MySQL将多个行和列拼接到单个行中
要将多个行和列拼接到单个行中,您可以使用GROUP_CONCAT()与CONCAT()。首先让我们创建一个表 –
mysql> create table DemoTable1463
-> (
-> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ClientName varchar(20),
-> ClientAge int
-> );
Query OK,0 rows affected (1.37 sec)
使用insert命令在表中插入一些记录 –
mysql> insert into DemoTable1463(ClientName,ClientAge) values('Adam Smith',34);
Query OK,1 row affected (0.13 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Doe',29);
Query OK,1 row affected (0.21 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('David Miller',NULL);
Query OK,1 row affected (0.28 sec)
mysql> insert into DemoTable1463(ClientName,ClientAge) values('John Smith',32);
Query OK,1 row affected (0.14 sec)
使用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)
阅读更多:MySQL 教程