DDL——学生表——成绩表
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学号',
`createDate` datetime DEFAULT NULL,
`userName` varchar(20) DEFAULT NULL,
`pwd` varchar(36) DEFAULT NULL,
`phone` varchar(11) DEFAULT NULL,
`age` tinyint(3) unsigned DEFAULT NULL,
`sex` char(2) DEFAULT '男',
`introduce` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `result` (
`rid` int(11) NOT NULL AUTO_INCREMENT COMMENT '成绩编号',
`testName` varchar(255) DEFAULT NULL COMMENT '测试名称',
`score` double(4,2) DEFAULT NULL COMMENT '成绩',
`studentId` int(11) DEFAULT NULL COMMENT '学生id',
PRIMARY KEY (`rid`),
KEY `studentId` (`studentId`),
CONSTRAINT `result_ibfk_1` FOREIGN KEY (`studentId`) REFERENCES `student` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DML
insert into student values(0,'2024-02-25 10:10:10','赵灵儿','123',
'15612345678',16,'女','逍遥哥哥,你终于找到我了。');
insert into student values(0,'2024-02-25 10:10:10','王语嫣','123',
'15612345678',17,'女','慕容复,我和你不共戴天。');
insert into student values(0,'2024-02-25 10:10:10','龙姑娘','123',
'15612345678',22,'女','我想过过过儿过过的日子。');
insert into student values(0,'2024-02-25 10:10:10','杨过','123',
'15612345678',18,'男','一遇杨过误终身。');
insert into student values(0,'2024-02-25 10:10:10','杨逍','123',
'15612345678',27,'男','杨过跟程英的大儿子。');
insert into student (userName,age,introduce)values('黄衣女子',26,'杨过与龙姑娘的大女儿。');
insert into result values(0,'政治',96,1);
insert into result values(0,'地理',86,5);
insert into result values(0,'政治',77,3);
insert into result values(0,'英语',99,3);
insert into result values(0,'历史',22,6);
insert into result values(0,'化学',69,2);
insert into result values(0,'Java',79,5);
insert into result values(0,'Java',67,6);
insert into result values(0,'政治',97,2);
insert into result values(0,'物理',76,6);
insert into result values(0,'物理',82,2);
insert into result values(0,'化学',56,4);
DQL
# 分组显示时,只有被分组的列数据有效,其余无效
select testName '学科成绩',
sum(score) '科目总分数',
count(score) '科目考试人数', avg(score) '科目平均分数',
max(score) '科目最高分',
min(score) '科目最低分'# 最后一个列信息不写【,】
from result
where studentId<4 # 具体的列信息筛选使用where
group by testName;# 分组
having avg(score)>90 # 聚合数据筛选必须使用having
-------------------------------------------------------------------------------------
# 分组显示时,只有被分组的列数据有效,其余无效
select studentId '学号',userName '学生姓名', introduce '学生简介',
sum(score) '学生各科目总成绩',
count(score) '学生参与科目考试数量',
avg(score) '学生所有科目平均分数',
max(score) '学生所有科目中最高分',
min(score) '学生所有科目中最低分'# 最后一个列信息不写【,】
from result INNER JOIN student on result.studentId=student.id # 去除笛卡尔积
where sex='男' # 具体的列信息筛选使用where
group by studentId,userName,introduce # 分组
having avg(score)<60 # 聚合数据筛选必须使用having
order by avg(score) desc;# order by 一定在后方,最后方是limit