使用 MySQL 将部分列值连接到一行中,并为每个字符串添加特定前缀“MR.”
CONCAT() 方法将用于将“MR”连接到每个字符串,而 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)
以下是连接字符串的查询 -
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)
广告