简体   繁体   English

MySQL 最后显示所有行和总和

[英]MySQL show all rows and sum at the end

I've read through about 20 different answers regarding this question, but either I'm mis-understanding the answers, or its just not clicking.关于这个问题,我已经阅读了大约 20 个不同的答案,但要么我误解了答案,要么只是没有点击。 Here is my situation:这是我的情况:

I have a table that lists ingredients for a recipe.我有一张列出食谱成分的表格。 Columns in the table are: ingredient_id, ingredient_title, ingredient_oz, ingredient_grams, ingredient_lbs (pounds), etc.表中的列有:ingredient_id, ingredient_title, ingredient_oz, ingredient_grams, ingredient_lbs(磅)等。

I want to list each ingredient, then after all ingredients have been listed, add a final row that sums up all the oz, grams, lbs, etc. Below is an example of the output I am trying to achieve.我想列出每种成分,然后在列出所有成分后,添加最后一行,总结所有盎司、克、磅等。下面是我试图实现的 output 的示例。

Example:例子:

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

TOTAL               14   12      11

My first thought was simply using SUM() AS in the SQL我的第一个想法是简单地在 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

And here is the code on my page:这是我页面上的代码:

<!-- 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 }?>

However all that does is return the first row (ingredient 1), and doesn't return the remaining rows or the sum.然而,它所做的只是返回第一行(成分 1),而不返回剩余的行或总和。 Then as I continued to read about this, I saw a low of people discussing using "group by" as well.然后当我继续阅读这篇文章时,我看到很少有人在讨论使用“group by”。 So then I tried:然后我尝试了:

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

That returns all the rows, but again doesn't return a sum.这将返回所有行,但同样不会返回总和。 Am I grouping by the wrong field?我是按错误的字段分组吗? Do I need to group each of the fields I'm trying to sum?我是否需要对要求和的每个字段进行分组?

When you run a query, you will get the data back that you ask for, so basically if you run a query to return all the rows individually - you will get those back, without the total.当你运行一个查询时,你会得到你要求的数据,所以基本上如果你运行一个查询来单独返回所有行 - 你会得到那些,没有总数。 If on the other hand you run a query to get only the sum/totals, you won't get the individual rows of data.另一方面,如果您运行查询以仅获取总和/总计,则不会获取单个数据行。

There are two ways to get what you want.有两种方法可以得到你想要的东西。 One is done via a query, one is done via PHP itself.一种是通过查询完成的,一种是通过 PHP 本身完成的。

You can write a union query to get the individual rows of data, then return the sums, something like this:您可以编写一个联合查询来获取各个数据行,然后返回总和,如下所示:

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

Which will return both.这将返回两者。

Or you can write a quick snippet of PHP code to do the addition for you in your code based on the first part of the query:或者,您可以编写一段 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.
?>

I would personally probably use the second approach - you don't need to make the database run the query twice just to get the results - and you are already getting all the individual rows of data, therefore you may as well simply keep a simple running total in a variable to be displayed as needed.我个人可能会使用第二种方法 - 你不需要让数据库运行两次查询来获得结果 - 而且你已经获得了所有单独的数据行,因此你也可以简单地保持一个简单的运行总计在一个变量中,根据需要显示。

Don't be afraid to run 2 separate SQL queries , because:不要害怕运行 2 个单独的 SQL 查询,因为:

  • Grouping (for sum) works differently分组(总和)的工作方式不同
  • Also code logic will more readable and decoupled代码逻辑也将更具可读性和解耦性

$query = "
  SELECT
    ingredient_title,
    ingredient_oz,
    ingredient_lbs,
    ingredient_grams
  FROM ingredients
";
$ingredients = $db->query($query)->fetch_all();

$query = "
  SELECT
    SUM(ingredient_oz) as oz_sum,
    SUM(ingredient_lbs) as lbs_sum,
    SUM(ingredient_grams) as grams_sum
  FROM ingredients
";
$ingredientSummary = $db->query($query)->fetch_assoc();


<!-- Beginning of table is here -->
<?php
foreach ($ingredients as $ingredientRow) ?>
  <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 $ingredientSummary["oz_sum"]; ?></td>
  <td><?php echo $ingredientSummary["lbs_sum"]; ?></td>
  <td><?php echo $ingredientSummary["grams_sum"]; ?></td>
</tr>
</tfoot>
</table>
<?php }?>

I think you should make it a separate query when selecting the sum.我认为您应该在选择总和时将其设为单独的查询。 Does it make sense that it can get the sum of each row when the sum is of all the rows ?当总和是所有行的总和时,它可以获得每行的总和是否有意义? By grouping you cause the SUM to sum each group, and every ingredient is a marked as a group.通过分组,您可以使 SUM 对每个组求和,并且每个成分都被标记为一个组。

its little late, but its easy with a roll back at the end of query有点晚了,但是在查询结束时回滚很容易

SELECT ingredient_title, ingredient_oz, ingredient_lbs, ingredient_grams
FROM ingredients
WITH ROLL BACK

here some examples from other site https://www.mysqltutorial.org/mysql-rollup/这里有一些来自其他网站的例子https://www.mysqltutorial.org/mysql-rollup/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM