mysql group_concat的使用

CREATE TABLE school.tb_class (
  id int UNSIGNED NOT NULL AUTO_INCREMENT,
  teacher varchar(20) DEFAULT NULL,
  student varchar(20) DEFAULT NULL,
  PRIMARY KEY (id)
)


insert INTO tb_class(teacher, student)VALUES('陈老师','张无忌');
insert INTO tb_class(teacher, student)VALUES('陈老师','赵敏');
insert INTO tb_class(teacher, student)VALUES('陈老师','周芷若');
insert INTO tb_class(teacher, student)VALUES('李老师','小昭');
insert INTO tb_class(teacher, student)VALUES('李老师','殷离');
insert INTO tb_class(teacher, student)VALUES('张老师','杨逍');
insert INTO tb_class(teacher, student)VALUES('张老师','丁敏君');

select * FROM tb_class

mysql group_concat的使用_第1张图片

 

-- 默认用法, 默认使用","分隔每组的学生
select teacher, group_concat(student)
from tb_class
group by teacher

 

-- 改成用"-"来分隔每组的学生
select teacher, group_concat(student separator '-')
from tb_class
group by teacher

 --每组的学生根据id倒序排列,同时修改分隔符为"-"

select teacher, group_concat(student order by id desc separator '-')
from tb_class
group by teacher

 

你可能感兴趣的:(1024程序员节)