MySQL++:MySQL 多行数据合并 GROUP_CONCAT

表结构及数据:

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  ;

MySQL++:MySQL 多行数据合并 GROUP_CONCAT

需求: 将每个人的课程合并为一行数据

select t.name as ‘姓名‘,GROUP_CONCAT(t.course_name )  as ‘课程‘ from course t  group by t.name ;

MySQL++:MySQL 多行数据合并 GROUP_CONCAT

 

修改分隔符及排序

select t.name as ‘姓名‘,GROUP_CONCAT(t.course_name  order by t.course_name SEPARATOR ‘#‘)  as ‘课程‘ from course t  group by t.name 

MySQL++:MySQL 多行数据合并 GROUP_CONCAT

注意:使用 GROUP_CONCAT()函数必须对源数据进行分组,否则所有数据会被合并成一行

 

MySQL++:MySQL 多行数据合并 GROUP_CONCAT

上一篇:任意阶魔方阵(幻方)的算法及C语言实现


下一篇:解决Navicat连接MySQL 1130问题