如何在 MySQL 中根据相应的重复 id 值连接列?在同一列中显示用斜线分隔的重复值
mysqlmysqli database更新于 2025/10/30 15:08:17
为此,您可以使用 GROUP_CONCAT()。
首先我们创建一个表 −
mysql> create table DemoTable764 ( ProductId int, ProductPrice int ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 −
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)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

