我有一个MySQL
表,其中有两列:amount (INT)
和address (string)
。
所有地址都以“A”或“B”开头。
如何计算地址以“A”开头的所有金额的总和以及地址以“B”开头的所有金额的总和?
我希望在PHP
中而不是直接在MySQL
中执行此操作。
答案 0 :(得分:0)
如果PHP
请求不是必需的,您只需使用SQL
即可。
您可以使用left
和group 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"];
}
?>