当前位置:   article > 正文

MySQL多表联合查询+分组+排序_mysql 多张表查询排序

mysql 多张表查询排序

 DDL——学生表——成绩表

  1. CREATE TABLE `student` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '学号',
  3. `createDate` datetime DEFAULT NULL,
  4. `userName` varchar(20) DEFAULT NULL,
  5. `pwd` varchar(36) DEFAULT NULL,
  6. `phone` varchar(11) DEFAULT NULL,
  7. `age` tinyint(3) unsigned DEFAULT NULL,
  8. `sex` char(2) DEFAULT '男',
  9. `introduce` varchar(255) DEFAULT NULL,
  10. PRIMARY KEY (`id`)
  11. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
  12. CREATE TABLE `result` (
  13. `rid` int(11) NOT NULL AUTO_INCREMENT COMMENT '成绩编号',
  14. `testName` varchar(255) DEFAULT NULL COMMENT '测试名称',
  15. `score` double(4,2) DEFAULT NULL COMMENT '成绩',
  16. `studentId` int(11) DEFAULT NULL COMMENT '学生id',
  17. PRIMARY KEY (`rid`),
  18. KEY `studentId` (`studentId`),
  19. CONSTRAINT `result_ibfk_1` FOREIGN KEY (`studentId`) REFERENCES `student` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
  20. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

DML

  1. insert into student values(0,'2024-02-25 10:10:10','赵灵儿','123',
  2. '15612345678',16,'女','逍遥哥哥,你终于找到我了。');
  3. insert into student values(0,'2024-02-25 10:10:10','王语嫣','123',
  4. '15612345678',17,'女','慕容复,我和你不共戴天。');
  5. insert into student values(0,'2024-02-25 10:10:10','龙姑娘','123',
  6. '15612345678',22,'女','我想过过过儿过过的日子。');
  7. insert into student values(0,'2024-02-25 10:10:10','杨过','123',
  8. '15612345678',18,'男','一遇杨过误终身。');
  9. insert into student values(0,'2024-02-25 10:10:10','杨逍','123',
  10. '15612345678',27,'男','杨过跟程英的大儿子。');
  11. insert into student (userName,age,introduce)values('黄衣女子',26,'杨过与龙姑娘的大女儿。');
  12. insert into result values(0,'政治',96,1);
  13. insert into result values(0,'地理',86,5);
  14. insert into result values(0,'政治',77,3);
  15. insert into result values(0,'英语',99,3);
  16. insert into result values(0,'历史',22,6);
  17. insert into result values(0,'化学',69,2);
  18. insert into result values(0,'Java',79,5);
  19. insert into result values(0,'Java',67,6);
  20. insert into result values(0,'政治',97,2);
  21. insert into result values(0,'物理',76,6);
  22. insert into result values(0,'物理',82,2);
  23. insert into result values(0,'化学',56,4);

DQL

  1. # 两个表的联合查询以及分组排序与having筛选
  2. select studentId '学号',userName '学生名称',
  3. sum(score) '学生各科目总分',
  4. count(score) '考试科目数量',
  5. avg(score) '各科目平均分'
  6. from result inner join student on result.studentId=student.id
  7. # 重新使用学号进行分组
  8. GROUP BY studentId,userName
  9. HAVING avg(score)>60
  10. order by avg(score) desc;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/596509
推荐阅读
相关标签
  

闽ICP备14008679号