根据php中另一列的条件为一列创建总和?

时间:2018-02-04 14:12:48

标签: php mysql

我有一个MySQL表,其中有两列:amount (INT)address (string)。 所有地址都以“A”或“B”开头。 如何计算地址以“A”开头的所有金额的总和以及地址以“B”开头的所有金额的总和?

我希望在PHP中而不是直接在MySQL中执行此操作。

2 个答案:

答案 0 :(得分:0)

如果PHP请求不是必需的,您只需使用SQL即可。

您可以使用leftgroup by

select left(address, 1) addr_part, sum(amount)
from my_table
group by addr_part

答案 1 :(得分:0)

直接在MySQL中执行此操作,请参阅scaisEdge's answer,这是我认为的方法,但由于您需要PHP解决方案,因此您可以尝试以下操作:

<?php
   # Create an array to store the results.
   $data = ["A" => 0, "B" => 0];

   # Initiate a db connection.
   $connection = new mysqli("localhost", "username", "password", "db");

   # Fetch the addresses and amounts from the database.
   $result = $connection -> query("SELECT `address`, `amount` FROM `table_name`");

   # Iterate over each row.
   while ($row = $result -> fetch_assoc()) {
      # Increment the value by the amount of the row.
      $data[$row["address"][0]] += $row["amount"];
   }
?>
相关问题