sql多表查询分组最大值
问题描述:有三张表:学生表Student(id,name),id为主键;课程表Subject(id,name),id为主键;分数表score(studentid,subjectid,score),其中studentId与subjectid为联合主键,一句sql语句查询出:学号,姓名,课程名,课程最高分.
模拟实现如下:
三张表:
CREATE TABLE student ( id INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(20) )
CREATE TABLE subjects( id INT PRIMARY KEY AUTO_INCREMENT, `name` VARCHAR(20) )
CREATE TABLE score( studentid INT REFERENCES student(id), subjectid INT REFERENCES subjects(id), score INT, PRIMARY KEY(studentid,subjectid) )
模拟插入的数据如下:
INSERT INTO student VALUES(NULL,'zhangSan'); INSERT INTO student VALUES(NULL,'liSi'); INSERT INTO subjects VALUES(NULL,'Chinese'); INSERT INTO subjects VALUES(NULL,'English'); INSERT INTO score VALUES(1,1,60); INSERT INTO score VALUES(1,2,90); INSERT INTO score VALUES(2,1,70); INSERT INTO score VALUES(2,2,80);
每个人解题都有自己的思路,我说一下我自己的思路:我认为难点在于要分组查询出每个学科的最高分,所有要先对score表进行查询,结果为每一个subjectid对应一个最高的score。首先,我想到的思路就是:得到相同学科的最高分数,再查询score表,找到最高分数的记录,代码如下:
SELECT * FROM score a WHERE score=(SELECT MAX(score) FROM score WHERE subjectid=a.subjectid)
只要做到这,相信剩下的就没有什么难度了,就是简单的多表查询了,不多说了,直接上完整的代码
SELECT st.id,st.name,sj.name,sc.score FROM student st,subjects sj, (SELECT * FROM score a WHERE score=(SELECT MAX(score) FROM score WHERE subjectid=a.subjectid)) sc WHERE st.id = sc.studentid AND sj.id = sc.subjectid
每个人的想法不一样,做法就不一样,如果大家有更好的解决办法,欢迎大家留言讨论!
快乐学习,快乐编程!