Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL为每行使用代数表达式求和_Mysql_Select_Sum - Fatal编程技术网

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中