如何在MySQL中共同使用GROUP_CONCAT()和CONCAT()连接字符串?
CONCAT()方法用于连接,而GROUP_CONCAT()用于连接组中一个字符串中的字符串。
让我们首先创建一个表 -
mysql> create table DemoTable799 ( UserId int, UserName varchar(100), UserAge int ); Query OK, 0 rows affected (0.56 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable799 values(101,'John',21); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable799 values(102,'Chris',26); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable799 values(101,'Robert',23); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable799 values(103,'David',24); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable799 values(101,'Mike',29); Query OK, 1 row affected (0.18 sec)
使用select语句从表显示所有记录 -
mysql> select *from DemoTable799;
这会产生以下输出 -
+--------+----------+---------+ | UserId | UserName | UserAge | +--------+----------+---------+ | 101 | John | 21 | | 102 | Chris | 26 | | 101 | Robert | 23 | | 103 | David | 24 | | 101 | Mike | 29 | +--------+----------+---------+ 5 rows in set (0.00 sec)
以下是使用CONCAT()和GROUP_CONCAT()连接字符串的查询 -
mysql> select UserId,GROUP_CONCAT(CONCAT('MR.', UserName)) from DemoTable799 group by UserId;
这会产生以下输出 -
+--------+---------------------------------------+ | UserId | GROUP_CONCAT(CONCAT('MR.', UserName)) | +--------+---------------------------------------+ | 101 | MR.John,MR.Robert,MR.Mike | | 102 | MR.Chris | | 103 | MR.David | +--------+---------------------------------------+ 3 rows in set (0.00 sec)
广告