为此,可以将GROUP_CONCAT()与GROUP BY子句一起使用。两者都用于对连续副本进行分组并在一行中显示。让我们首先创建一个表-
create table DemoTable ( StudentFavouriteSubject varchar(40), StudentName varchar(40) ) ;
使用插入命令在表中插入一些记录-
insert into DemoTable values('MySQL','Chris'); insert into DemoTable values('MongoDB','Bob'); insert into DemoTable values('MySQL','Sam'); insert into DemoTable values('Java','Mike'); insert into DemoTable values('C','Carol'); insert into DemoTable values('MongoDB','John');
使用select语句显示表中的所有记录-
select *from DemoTable;
这将产生以下输出-
+-------------------------+-------------+ | StudentFavouriteSubject | StudentName | +-------------------------+-------------+ | MySQL | Chris | | MongoDB | Bob | | MySQL | Sam | | Java | Mike | | C | Carol | | MongoDB | John | +-------------------------+-------------+ 6 rows in set (0.00 sec)
以下是查找重复项并单行显示的查询-
select group_concat(StudentName),StudentFavouriteSubject from DemoTable group by StudentFavouriteSubject;
这将产生以下输出-
+---------------------------+-------------------------+ | group_concat(StudentName) | StudentFavouriteSubject | +---------------------------+-------------------------+ | Carol | C | | Mike | Java | | Bob,John | MongoDB | | Chris,Sam | MySQL | +---------------------------+-------------------------+ 4 rows in set (0.00 sec)