代码:
完整代码: select stu_name,
ifnull(sum(lesson_name="语文")*score,0) 语文,
ifnull(sum(lesson_name="数学")*score,0) 数学,
ifnull(sum(lesson_name="英语")*score,0) 英语,
ifnull(sum(lesson_name="物理")*score,0) 物理,
ifnull(sum(lesson_name="化学")*score,0) 化学,
sum(score) 总分
from (select stu_id,stu_name,lesson_name,lesson_id
from t_stu_profile,t_lesson
where class_id='0611' and gender="M") t
left join t_score
on t.stu_id=t_score.stu_id and t.lesson_id=t_score.lesson_id;
图表:
代码修改如下:
第一处改成内连接,第二处加group by stu_name。
左边是笛卡尔积,遍历了所有情况,比如张三和所有课程拼接, 但是张三没有学所有的课,只是学了部分,最后用内连接把没学过的课程去掉,
另外这种写法我个人不太建议用,一个是逻辑复杂,另外计算量比较大,如果数据有很多,速度会慢。
推荐使用下面这个方法:
在第一节基础上 更新了函数和执行顺序:实操了字符数函数、时间函数、字段截取函数、interval函数等,除最后顺序实操因未导入数据库,导致无法执行