建表语句:students.sql
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for students
-- ----------------------------
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
`id` int(3) NOT NULL AUTO_INCREMENT COMMENT '编号',
`name` varchar(255) COLLATE utf8_bin NOT NULL COMMENT '姓名',
`age` int(2) DEFAULT NULL COMMENT '年龄',
`height` double(5,0) DEFAULT NULL COMMENT '身高',
`gender` varchar(5) COLLATE utf8_bin DEFAULT NULL COMMENT '性别',
`cls_id` int(1) DEFAULT NULL COMMENT '班级编号',
`is_delete` varchar(1) COLLATE utf8_bin DEFAULT NULL COMMENT '是否删除',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-- ----------------------------
-- Records of students
-- ----------------------------
INSERT INTO `students` VALUES ('1', '小明', '18', '180', '男', '1', '');
INSERT INTO `students` VALUES ('2', '小月', '18', '180', '女', '2', null);
INSERT INTO `students` VALUES ('3', '彭于晏', '29', '185', '男', '1', null);
INSERT INTO `students` VALUES ('4', '刘德华', '59', '175', '男', '2', null);
INSERT INTO `students` VALUES ('5', '黄蓉', '38', '160', '女', '1', null);
INSERT INTO `students` VALUES ('6', '凤姐', '28', '155', '保密', '2', null);
INSERT INTO `students` VALUES ('7', '王祖贤', '18', '172', '女', '1', null);
INSERT INTO `students` VALUES ('8', '刘亦菲', '30', '168', '女', '2', null);
INSERT INTO `students` VALUES ('9', '金星', '35', '170', '保密', '3', null);
INSERT INTO `students` VALUES ('10', '郭靖', '38', '175', '男', '4', null);
INSERT INTO `students` VALUES ('11', '大刘', '39', '175', '男', '5', null);
1.1)查询年龄在18-34之间的男性。按照年龄从小到大排序
SELECT * FROM students WHERE (age BETWEEN 18 AND 35) AND gender = '男' ORDER BY age ASC;
表如下所示:
1.2)查询年龄在18-34之间的女性,年龄从大到小排序,年龄相同的情况下按照身高从高到矮排序
SELECT * FROM students WHERE (age BETWEEN 18 AND 35) AND gender = '女' ORDER BY age DESC,height DESC;
- 总数:count ,查询男性和女性人数
- 最小值: min ;
- 最大值:max;
- 平均值:avg—计算平均年龄— sum(age) / count(*)
- 四舍五入:round(123.45 , 1) 保留一位小数
2.1)查询男性人数
SELECT COUNT(*) AS 男性人数 FROM students WHERE gender = '男'
SELECT MAX(age) AS 年龄最大值 FROM students;
SELECT SUM(age) AS 年龄总和 FROM students;
SELECT ROUND(AVG(age),2) AS 年龄平均值 FROM students;
SELECT ROUND(SUM(age)/COUNT(*),2) AS 年龄平均值 FROM students;
3.1)通常和聚合函数结合起来使用
SELECT ... FROM students GROUP BY gender;
... 中放置能够唯一区分按照gender分组的条件
SELECT gender AS 性别 FROM students GROUP BY gender;
SELECT gender AS 性别 ,COUNT(*) AS 人数 FROM students GROUP BY gender;
SELECT gender AS 性别 ,GROUP_CONCAT(name) AS 姓名 FROM students GROUP BY gender;
SELECT gender AS 性别 ,COUNT(*) AS 人数 FROM students WHERE gender = '男' GROUP BY gender;
SELECT gender AS 性别 ,GROUP_CONCAT(id,"_",name,"_",age) AS 编号_姓名_年龄 FROM students WHERE gender = '男' GROUP BY gender;
SELECT gender AS 性别 ,GROUP_CONCAT(name) AS 姓名 ,AVG(age) FROM students GROUP BY gender HAVING AVG(age) > 30;
SELECT gender AS 性别 ,GROUP_CONCAT(name) AS 姓名 FROM students GROUP BY gender HAVING COUNT(*) > 2;
关注公众号,回复 【算法】,获取高清算法书!