如何在同一个 MySQL 查询中同时使用 GROUP_CONCAT() 和 CONCAT() 连接字符串?
mysqlmysqli database
CONCAT() 方法用于连接,而 GROUP_CONCAT() 用于将来自一个组的字符串连接到一个字符串中。
首先我们创建一个表 −
mysql> create table DemoTable799 ( UserId int, UserName varchar(100), UserAge int ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 −
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)