MySQL用每行的代数表达式求和

时间:2012-05-16 01:46:36

标签: mysql select sum

让我们做对了。

这会返回正确的结果:

SELECT sum(w.weight * w.repetitions)
FROM workout_exercise_logs w
JOIN workout_logs wo ON `w`.`workoutLogID`=`wo`.`workoutLogID`
JOIN workouts wor ON `wo`.`workoutID`=`wor`.`workoutID`
WHERE w.weightType=1 and `wor`.`userID`=34

但是当我添加+ w.weight * w.seconds / 3时,我得到NULL结果:

SELECT sum(w.weight * w.repetitions + w.weight * w.seconds / 3)
FROM workout_exercise_logs w
JOIN workout_logs wo ON `w`.`workoutLogID`=`wo`.`workoutLogID`
JOIN workouts wor ON `wo`.`workoutID`=`wor`.`workoutID`
WHERE w.weightType=1 and `wor`.`userID`=34

表达式有什么问题,我该如何解决?谢谢!

1 个答案:

答案 0 :(得分:2)

一个问题,你是否真的需要这个字段可以为空(或任何字段):秒?

如果这是一项要求,则需要将那些可以为空的字段合并为零:

SELECT sum(
      w.weight * w.repetitions 
      + w.weight * coalesce(w.seconds,0) / 3)
FROM workout_exercise_logs w
JOIN workout_logs wo ON `w`.`workoutLogID`=`wo`.`workoutLogID`
JOIN workouts wor ON `wo`.`workoutID`=`wor`.`workoutID`
WHERE w.weightType=1 and `wor`.`userID`=34