我正在尝试显示当前正在使用多个MySQL查询的摘要表,我想知道是否可以将它们合并为一个。
我有一个名为'payment'的表,其中包含字段金额和货币,我正在尝试显示每种货币的汇总总表。举个例子:
<table>
<tr>
<td>USD</td>
<td>EUR</td>
<td>GBP</td>
</tr>
<tr>
<? $q1 = mysqli_query("SELECT sum(amount) as total_USD from payments WHERE currency='USD'");
while($row1 = mysqli_fetch_assoc($q1)){ ?>
<td><? echo number_format($row1['total_USD'],0); ?></td>
<? } ?>
<? $q2 = mysqli_query("SELECT sum(amount) as total_EUR from payments WHERE currency='EUR'");
while($row2 = mysqli_fetch_assoc($q2)){ ?>
<td><? echo number_format($row2['total_EUR'],0); ?></td>
<? } ?>
<? $q3 = mysqli_query("SELECT sum(amount) as total_GBP from payments WHERE currency='GBP'");
while($row3 = mysqli_fetch_assoc($q3)){ ?>
<td><? echo number_format($row3['total_GBP'],0); ?></td>
<? } ?>
</tr>
</table>
实际上,我使用的是12种货币,因此我有12个单独的查询,但感觉效率低下,所以我想知道是否有更简单的方法来实现相同的结果?
非常感谢!
答案 0 :(得分:3)
SELECT currency,
SUM(amount) as total
FROM payments
GROUP BY currency
答案 1 :(得分:2)
Solution 1:
SELECT currency, SUM(amount) as total FROM payments GROUP BY currency
Solution 2 :
$currencies=array(USD,EUR,GBP,...);
foreach($currencies as $currency){
$q1= mysqli_query("SELECT sum(amount) as total from payments WHERE currency='".$currency."'");
while($row1 = mysqli_fetch_assoc($q1)){
echo number_format($row1['total'],0);
}
}
答案 2 :(得分:1)
您可以在此处使用GROUP BY。
SELECT currency, SUM(amount) as total FROM payments GROUP BY currency
http://dev.mysql.com/doc/refman/5.1/en/group-by-modifiers.html