1

我正在尝试显示一个当前使用多个 MySQL 查询的汇总表,我想知道是否可以将它们组合成一个。

我有一个名为“付款”的表格,其中包含字段金额和货币,我正在尝试显示每种货币的汇总表。举个例子:

<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 个单独的查询,但感觉效率低下,所以我想知道是否有更简单的方法来实现相同的结果?

非常感谢!

4

3 回答 3

3
SELECT currency,
       SUM(amount) as total
  FROM payments
 GROUP BY currency
于 2013-04-13T09:54:35.983 回答
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); 
       } 
    }
于 2013-04-13T10:07:00.647 回答
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

于 2013-04-13T09:55:20.290 回答