获取字段的总和乘以每个字段的数量

8cdiaqws  于 2021-06-15  发布在  Mysql
关注(0)|答案(0)|浏览(260)

我想计算sql表中一些字段(卡路里、碳水化合物、脂肪、蛋白质、盐和糖)的总和。我有另一个字段叫做quantity,我想用它来乘以每个字段的值,然后再将它们相加。但是,我得到一个错误,服务器无法及时响应我的请求。数量来自用户自己输入的文本输入。默认值为1。

<form method="POST" action="/topic7/mid-term/calculate">
                <% availableFood.forEach(function(food_item){ %>
                        <td><input type="checkbox" name="checkbox[]" value= <%= food_item.name %>></td>    
                        <td><input id="qty" type="text" name="qty" value="1" style="width: 30px;"/></td>
                        <td><%= food_item.name %></td>
                        <td><%= food_item.typical_values %></td> 
                        <td><%= food_item.unit_of_the_typical_value %></td>
                        <td><%= food_item.calories %></td>
                        <td><%= food_item.carbs %></td>
                        <td><%= food_item.fat %></td>
                        <td><%= food_item.protein %></td> 
                        <td><%= food_item.salt %></td> 
                        <td><%= food_item.sugar %></td>
                <% }) %>                     
        <p><input type="submit" value="Calculate sum" /></p>
</form>
app.post("/calculate", function (req, res) {
        let sqlquery = "
SELECT SUM(?*calories) AS calories
     , SUM(?*carbs) AS carbs
     , SUM(?*fat) AS fat
     , SUM(?*protein) As protein
     , SUM(?*salt) As salt
     , SUM(?*sugar) As sugar 
  FROM food_item 
 WHERE name IN (?)
";
        let sum = [req.body.qty, req.body.qty, req.body.qty, req.body.qty,
                   req.body.qty, req.body.qty, req.param('checkbox')];

        db.query(sqlquery, sum, (err, result) => {
            if (err) {
                return console.error(err.message);
            }else{
                res.send(" The nutritional information and calorie count of "+ req.param('checkbox') + " is: " + JSON.stringify(result));
            }
        });
    });

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题