[英]Formula/Query returns “wrong” result
我得到了以前的問題/問題的幫助,並且意識到我給出的腳本返回“錯誤”的數字/值(但不會觸發php / mysql錯誤)。 這是價值觀:
成分#1: 20.216卡路里
成分#2: 134.4564卡路里
腳本應返回: 154.67但返回: 91.35
編碼:
<?php
//The Recipe selected
$recipe_id = $_POST['recipe_id'];
/*****************************************
* Total CALORIES in this recipe
*****************************************/
echo '<h4>Total calories in this recipe:</h4>';
$result = mysql_query(
"SELECT SUM(ingredient_calories), ingredient_amount
FROM recipe_ingredients
INNER JOIN ingredients USING (ingredient_id)
WHERE recipe_id = $recipe_id");
while ($row = mysql_fetch_array($result)) {
$recipe_calories = (
$row['SUM(ingredient_calories)']
* $row['ingredient_amount']);
}
echo number_format($recipe_calories, 2);
mysql_free_result($result);
?>
成分表,存儲每種成分的默認值和份量。
食譜表,存儲/設置recipe_id,以及與查詢無關的其他數據)
recipe_ingredients表,映射配方中的成分並存儲配方中使用的量。
我確定這是一個查詢問題,但我太捂着耳朵來確定問題。 任何幫助是極大的贊賞 :)
更新:這是表格數據,按要求
ingredients
-----------
ingredient_id
ingredient_name
ingredient_calories
recipes
-------
recipe_id
recipe_name
recipe_ingredients
------------------
recipe_id (fk)
ingredient_id (fk)
ingredient_amount
你不想要這個:
SELECT SUM(ingredient_calories), ingredient_amount
在一列而不是另一列上使用SUM
可能是您的錯誤所在。 事實上,當我在mysql(5.0.51a)中嘗試此查詢時,我只是收到錯誤。
ERROR 1140 (42000): Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no
GROUP columns is illegal if there is no GROUP BY clause
改為:
SELECT SUM(ingredient_calories * ingredient_amount)
並從php中的單個結果行中獲取該單個列:
$row = mysql_fetch_array($result)
$recipe_calories = $row[0]
這是猜測,因為您實際上沒有說明問題所在,但是,結果中的每一行都會覆蓋$recipe_calories
。 也許你的意思是:
$recipe_calories = 0;
while ($row = mysql_fetch_array($result)) {
$recipe_calories += (
$row['SUM(ingredient_calories)']
* $row['ingredient_amount']);
}
雖然您應該在SQL中完成所有操作 - 但不需要使用PHP進行計算。
弄清楚了!
做了以下調整:
$result = mysql_query(
"SELECT ingredient_calories, ingredient_amount
FROM recipe_ingredients
INNER JOIN ingredients USING (ingredient_id)
WHERE recipe_id = $recipe_id");
while ($row = mysql_fetch_array($result)) {
$recipe_calories += (
$row['ingredient_calories']
* $row['ingredient_amount']);
}
echo number_format($recipe_calories, 2);
問題解決了 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.