在 MySQL 中检查多条记录中列值是否相同,并将这些记录用特殊字符分隔在同一行中
为此,您可以使用 GROUP_CONCAT() 以及 DISTINCT。让我们先创建一个表 -
mysql> create table DemoTable ( Id int, Subject varchar(40) ); Query OK, 0 rows affected (0.56 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values(100,'MySQL'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(100,'MongoDB'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(100,'Java'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(100,'MongoDB'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(101,'MySQL'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(101,'MySQL'); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+------+---------+ | Id | Subject | +------+---------+ | 100 | MySQL | | 100 | MongoDB | | 100 | Java | | 100 | MongoDB | | 101 | MySQL | | 101 | MySQL | +------+---------+ 6 rows in set (0.00 sec)
以下是检查列值在多条记录中是否相同并将这些记录用特殊字符分隔在同一行的查询。这里的分隔符是连字符 -
mysql> select Id,group_concat(distinct Subject separator '-') as Subject from DemoTable group by Id;
这将产生以下输出 -
+------+--------------------+ | Id | Subject | +------+--------------------+ | 100 | Java-MongoDB-MySQL | | 101 | MySQL | +------+--------------------+ 2 rows in set (0.04 sec)
广告