如何在 MySQL 中根据对应的重复 id 值连接列?将同一列中的重复值以斜杠分隔显示
为此,可以使用 GROUP_CONCAT()。
让我们先创建一个表 -
mysql> create table DemoTable764 ( ProductId int, ProductPrice int ); Query OK, 0 rows affected (0.56 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable764 values(101,10000); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable764 values(102,1090); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable764 values(103,4000); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable764 values(102,3450); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable764 values(101,20000); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable764 values(104,50000); Query OK, 1 row affected (0.12 sec)
使用 select 语句从表中显示所有记录 -
mysql> select *from DemoTable764;
这将产生以下输出 -
+-----------+--------------+ | ProductId | ProductPrice | +-----------+--------------+ | 101 | 10000 | | 102 | 1090 | | 103 | 4000 | | 102 | 3450 | | 101 | 20000 | | 104 | 50000 | +-----------+--------------+ 6 rows in set (0.00 sec)
以下是连接具有相应重复 id 值的列的查询 -
mysql> select ProductId, group_concat(ProductPrice SEPARATOR '/') AS ProductPrice from DemoTable764 group by ProductId;
这将产生以下输出 -
+-----------+---------------+ | ProductId | ProductPrice | +-----------+---------------+ | 101 | 10000/20000 | | 102 | 1090/3450 | | 103 | 4000 | | 104 | 50000 | +-----------+---------------+ 4 rows in set (0.00 sec)
广告