網上查了很多好像說的都對,但是囉嗦,我看着都費勁
在現實的應用場景中:
如果想要統計每個班的男生/女生的數量就可以group by 班級id,性別
代碼如下
SELECT
class.`name`,
(case when students.sex=1 then '男' else '女' end) AS sex1,
COUNT(students.id)
FROM
students
LEFT JOIN class ON students.classId = class.id
GROUP BY class.id,students.sex;
具體重現:
1.班級表:
DROP TABLE IF EXISTS `class`;
CREATE TABLE `class` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '班級id',
`name` varchar(250) DEFAULT NULL COMMENT '班級名稱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='班級表';
-- ----------------------------
-- Records of class
-- ----------------------------
INSERT INTO `class` VALUES ('1', '一班');
INSERT INTO `class` VALUES ('2', '二班');
2.學生表:
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
`name` varchar(50) DEFAULT NULL COMMENT '學習姓名',
`age` int(3) DEFAULT NULL COMMENT '學生年齡',
`sex` int(1) DEFAULT NULL,
`classId` int(11) DEFAULT NULL COMMENT '所屬班級id',
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '學生id',
PRIMARY KEY (`id`),
KEY `FK_Reference_1` (`classId`),
CONSTRAINT `FK_Reference_1` FOREIGN KEY (`classId`) REFERENCES `class` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COMMENT='學生信息表';
-- ----------------------------
-- Records of students
-- ----------------------------
INSERT INTO `students` VALUES ('姓名11', '15', '1', '1', '3');
INSERT INTO `students` VALUES ('姓名12', '16', '2', '1', '4');
INSERT INTO `students` VALUES ('姓名13', '15', '1', '1', '5');
INSERT INTO `students` VALUES ('姓名21', '15', '1', '2', '8');
INSERT INTO `students` VALUES ('姓名22', '15', '2', '2', '9');
INSERT INTO `students` VALUES ('姓名23', '15', '2', '2', '10');
3.查詢:
SELECT
class.`name`,
(case when students.sex=1 then '男' else '女' end) AS sex1,
COUNT(students.id)
FROM
students
LEFT JOIN class ON students.classId = class.id
GROUP BY class.id,students.sex;