今天看一个mysql教程,看到一个例子,感觉里面的解决方案不是很合理。
问题如下:
有学生表:

成绩表:

想要查询出的效果:

其实就是原来是一个分数一条记录,现在变成一个学生一条记录。
那个教程里的sql如下:
1select a.id as 学号, a.name as 姓名, 2(case when b.kemu='语文' then score else 0 end) as 语文, 3(case when b.kemu='数学' then score else 0 end) as 数学, 4(case when b.kemu='英语' then score else 0 end) as 英语 5from student a, grade b 6where a.id = b.id
实现的效果:

很明显,每个学生的每个成绩都是单独一条记录,那和原来没有什么区别嘛。
改进后的sql如下:
1SELECT s.id, s.name, 2max(case when g.kemu='语文' then score else 0 end) as 语文, 3max(case when g.kemu='数学' then score else 0 end) as 数学, 4max(case when g.kemu='英语' then score else 0 end) as 英语, 5sum(score) as 总分, 6avg(score) as 平均分 7from student s LEFT JOIN grade g ON s.id = g.s_id GROUP BY s.id
就是使用了聚合函数,效果如下:

是不是比原来的效果好很多了呢