MySQL为每行使用代数表达式求和
让我们直接开始吧 这将返回正确的结果:MySQL为每行使用代数表达式求和,mysql,select,sum,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 但
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
表达式有什么问题,如何修复?谢谢 一个问题,您是否真的需要此字段为空(或任何相关字段):秒 如果这是一项要求,则需要将这些可为空的字段合并为零:
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
您还可以使用IFNULL而不是coalesce。@谢谢MajidTaheri,我无法立即回忆起该函数名。我知道在Sql Server中,它是空的。但我当然知道coalesce在几乎所有的数据库平台上都能工作ツ是的,在MySQL中