表结构及数据
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`course_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES ('李明', '阅读赏析');
INSERT INTO `course` VALUES ('李明', '摄影');
INSERT INTO `course` VALUES ('李明', '太极剑');
INSERT INTO `course` VALUES ('司马光', '马克思主义基本原理');
INSERT INTO `course` VALUES ('司马光', '摄影');
INSERT INTO `course` VALUES ('叶问', '阅读赏析');
INSERT INTO `course` VALUES ('叶问', '法语');
SET FOREIGN_KEY_CHECKS = 1;
选修课程表
select t.name as '姓名',t.course_name as '课程' from course t ;
需求: 将每个人的课程合并为一行数据
select t.name as '姓名',GROUP_CONCAT(t.course_name ) as '课程' from course t group by t.name ;
修改分隔符及排序
select t.name as '姓名',GROUP_CONCAT(t.course_name order by t.course_name SEPARATOR '#') as '课程' from course t group by t.name
注意:使用 GROUP_CONCAT()函数必须对源数据进行分组,否则所有数据会被合并成一行