(2)mysql--查詢部門人數最多的部門
阿新 • • 發佈:2018-12-24
1、函式count() + group by。
2、having 字句查詢。
3、建立的表結構,以及新增的資料如下sql。
-- ----------------------------
-- Table structure for employee_info
-- ----------------------------
DROP TABLE IF EXISTS `employee_info`;
CREATE TABLE `employee_info` (
`employee_id` int(10) NOT NULL,
`department_id` int(10) NOT NULL,
PRIMARY KEY (`employee_id`,`department_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- ----------------------------
-- Records of employee_info
-- ----------------------------
INSERT INTO `employee_info` VALUES ('1', '2');
INSERT INTO `employee_info` VALUES ('2', '2');
INSERT INTO `employee_info` VALUES (' 3', '2');
INSERT INTO `employee_info` VALUES ('4', '1');
INSERT INTO `employee_info` VALUES ('5', '1');
INSERT INTO `employee_info` VALUES ('6', '2');
INSERT INTO `employee_info` VALUES ('7', '2');
INSERT INTO `employee_info` VALUES ('8', '2');
INSERT INTO `employee_info` VALUES ('9', '2');
INSERT INTO `employee_info` VALUES (' 10', '2');
INSERT INTO `employee_info` VALUES ('11', '2');
INSERT INTO `employee_info` VALUES ('12', '2');
INSERT INTO `employee_info` VALUES ('13', '3');
INSERT INTO `employee_info` VALUES ('14', '3');
INSERT INTO `employee_info` VALUES ('15', '3');
INSERT INTO `employee_info` VALUES ('16', '3');
INSERT INTO `employee_info` VALUES ('17', '3');
INSERT INTO `employee_info` VALUES ('18', '3');
INSERT INTO `employee_info` VALUES ('19', '3');
INSERT INTO `employee_info` VALUES ('20', '3');
INSERT INTO `employee_info` VALUES ('21', '3');
INSERT INTO `employee_info` VALUES ('22', '3');
INSERT INTO `employee_info` VALUES ('23', '3');
思路
1)首先是根據部門id彙總部門人數。
select COUNT(employee_id) as number ,department_id from employee_info group by department_id
2)group by後面不能用where , 可以用having字句,所以最終sql如下。
select COUNT(employee_id) as number ,department_id from employee_info group by department_id HAVING number>=10;
總結:
路漫漫其修遠兮,吾將上下而求索。
如果遇到這樣的題,應該把大的問題一個個分散成小問題,然後一個個的解決小問題,然後拼湊起來,大問題就可以解決了。