gpt4 book ai didi

php - MySQL 在末尾显示所有行和总和

转载 作者:可可西里 更新时间:2023-11-01 07:58:46 24 4
gpt4 key购买 nike

关于这个问题,我已经阅读了大约 20 个不同的答案,但要么是我误解了答案,要么只是没有点击。这是我的情况:

我有一张表格,其中列出了食谱的成分。表格中的列有:ingredient_id, ingredient_title, ingredient_oz, ingredient_grams, ingredient_lbs(磅)等。

我想列出每种成分,然后在列出所有成分后,添加最后一行,总结所有盎司、克、磅等。下面是我试图实现的输出示例。

例子:

INGREDIENT TITLE    OZ   GRAMS   LBS
ingredient1 4 6 3
ingredient2 1 2 4
ingredient3 9 4 4

TOTAL 14 12 11

我的第一个想法是简单地在 SQL 中使用 SUM() AS

SELECT ingredient_title, ingredient_oz, ingredient_lbs, ingredient_grams, SUM(ingredient_oz) as oz_sum, SUM(ingredient_lbs) as lbs_sum, SUM(ingredient_grams) as grams_sum FROM ingredients

这是我页面上的代码:

<!-- Beginning of table is here -->
<?php
while ($ingredientRow = $ingredients->fetch_assoc()) { ?>
<tr>
<td><?php echo $ingredientRow["ingredient_title"]; ?></td>
<td><?php echo $ingredientRow["ingredient_oz"]; ?></td>
<td><?php echo $ingredientRow["ingredient_lbs"]; ?></td>
<td><?php echo $ingredientRow["ingredient_grams"]; ?></td>
</tr>
<?php } ?>
</tbody>
<tfoot>
<tr>
<td>TOTALS</td>
<td><?php echo $ingredientRow["oz_sum"]; ?></td>
<td><?php echo $ingredientRow["lbs_sum"]; ?></td>
<td><?php echo $ingredientRow["grams_sum"]; ?></td>
</tr>
</tfoot>
</table>
<?php }?>

然而,它所做的只是返回第一行(成分 1),而不返回其余行或总和。然后当我继续阅读这篇文章时,我看到很少有人在讨论使用“group by”。于是我尝试了:

SELECT ingredient_title, ingredient_oz, ingredient_lbs, ingredient_grams, SUM(ingredient_oz) as oz_sum, SUM(ingredient_lbs) as lbs_sum, SUM(ingredient_grams) as grams_sum FROM ingredients GROUP BY ingredient_title

这会返回所有行,但同样不会返回总和。我是按错误的字段分组吗?我是否需要对要求和的每个字段进行分组?

最佳答案

当您运行查询时,您将取回您要求的数据,因此基本上,如果您运行查询以单独返回所有行 - 您将取回那些数据,而不是总计。另一方面,如果您运行查询以仅获取总和/总计,则您将无法获取单独的数据行。

有两种方法可以得到你想要的。一种是通过查询完成的,一种是通过 PHP 本身完成的。

您可以编写联合查询来获取单独的数据行,然后返回总和,如下所示:

SELECT 
ingredient_title,
ingredient_oz,
ingredient_lbs,
ingredient_grams
FROM
ingredients
union all
SELECT
ingredient_title,
SUM(ingredient_oz) as oz_sum,
SUM(ingredient_lbs) as lbs_sum,
SUM(ingredient_grams) as grams_sum
FROM
ingredients

这将返回两者。

或者您可以编写一小段 PHP 代码,根据查询的第一部分在您的代码中为您执行添加操作:

<?php

$sql="SELECT
ingredient_title,
ingredient_oz,
ingredient_lbs,
ingredient_grams
FROM
ingredients";
//Execute query:
while($result)
{
echo $result['ingredient_title'];
echo $result['ingredient_oz'];
// etc etc. Format as needed...
$ingOz+=$result['ingredient_oz'];
$ingLbs+=$result['ingredient_lbs'];
$ingGrams+=$result['ingredient_grams'];
}
// And now the totals:
echo $ingOz;
echo $ingLbs;
// etc etc.
?>

我个人可能会使用第二种方法——你不需要让数据库运行两次查询来获得结果——而且你已经获得了所有单独的数据行,因此你也可以简单地保持变量中的简单运行总计,根据需要显示。

关于php - MySQL 在末尾显示所有行和总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26187579/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com