如何将重复的值合并成一个,并使用连字符在 MySQL 中将相应的值分隔开?
要合并,使用 GROUP_CONCAT() 函数将两行中的某些属性合并为一行。作为分隔符,使用连字符。
首先让我们创建一个表 -
mysql> create table DemoTable1386 -> ( -> Title varchar(255), -> Name varchar(60) -> ); Query OK, 0 rows affected (0.67 sec)
使用插入命令向表中插入一些记录 -
mysql> insert into DemoTable1386 values('Introduction to MySQL','Paul DuBois'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1386 values('Java in Depth','Khalid Mughal'); Query OK, 1 row affected (0.48 sec) mysql> insert into DemoTable1386 values('Introduction to MySQL','Russell Dyer'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1386 values('Java in Depth','Joshua Bloch'); Query OK, 1 row affected (0.17 sec)
使用选择语句显示表中的所有记录 -
mysql> select * from DemoTable1386;
这将产生以下结果 -
+-----------------------+---------------+ | Title | Name | +-----------------------+---------------+ | Introduction to MySQL | Paul DuBois | | Java in Depth | Khalid Mughal | | Introduction to MySQL | Russell Dyer | | Java in Depth | Joshua Bloch | +-----------------------+---------------+ 4 rows in set (0.00 sec)
以下是合并重复值的查询 -
mysql> select Title,group_concat(Name separator '----') from DemoTable1386 -> group by Title;
这将产生以下结果 -
+-----------------------+-------------------------------------+ | Title | group_concat(Name separator '----') | +-----------------------+-------------------------------------+ | Introduction to MySQL | Paul DuBois----Russell Dyer | | Java in Depth | Khalid Mughal----Joshua Bloch | +-----------------------+-------------------------------------+ 2 rows in set (0.00 sec)
广告