为此,请使用GROUP_CONCAT()。让我们首先创建一个表-
create table DemoTable2024 -> ( -> SubjectName varchar(20), -> StudentName varchar(20) -> );
使用插入命令在表中插入一些记录-
insert into DemoTable2024 values('MySQL','Chris'); insert into DemoTable2024 values('MySQL','David'); insert into DemoTable2024 values('MongoDB','Bob'); insert into DemoTable2024 values('Java','Sam'); insert into DemoTable2024 values('MongoDB','Mike');
使用select语句显示表中的所有记录-
select *from DemoTable2024;
这将产生以下输出-
+-------------+-------------+ | SubjectName | StudentName | +-------------+-------------+ | MySQL | Chris | | MySQL | David | | MongoDB | Bob | | Java | Sam | | MongoDB | Mike | +-------------+-------------+ 5 rows in set (0.00 sec)
以下是将不同行中的列表返回到单个字段中的查询-
select SubjectName,group_concat(StudentName) -> from DemoTable2024 -> group by SubjectName;
这将产生以下输出-
+-------------+---------------------------+ | SubjectName | group_concat(StudentName) | +-------------+---------------------------+ | Java | Sam | | MongoDB | Bob,Mike | | MySQL | Chris,David | +-------------+---------------------------+ 3 rows in set (0.06 sec)