mysql查询每个学生的各科成绩,以及总分和平均分
今天看一个mysql教程,看到一个例子,感觉里面的解决方案不是很合理。 问题如下: 有学生表: 成绩表: 想要查询出的效果:
其实就是原来是一个分数一条记录,现在变成一个学生一条记录。 那个教程里的sql如下:
select a.id as 学号, a.name as 姓名, (case when b.kemu=语文 then score else 0 end) as 语文, (case when b.kemu=数学 then score else 0 end) as 数学, (case when b.kemu=英语 then score else 0 end) as 英语 from student a, grade b where a.id = b.id
实现的效果: 很明显,每个学生的每个成绩都是单独一条记录,那和原来没有什么区别嘛。 改进后的sql如下:
SELECT s.id, s.name, max(case when g.kemu=语文 then score else 0 end) as 语文, max(case when g.kemu=数学 then score else 0 end) as 数学, max(case when g.kemu=英语 then score else 0 end) as 英语, sum(score) as 总分, avg(score) as 平均分 from student s LEFT JOIN grade g ON s.id = g.s_id GROUP BY s.id
就是使用了聚合函数,效果如下: 是不是比原来的效果好很多了呢
