简体   繁体   中英

Combining multiple MySQL queries into 1

I am trying to display a summary table which is currently using multiple MySQL queries and I was wondering if it's possible to combine them into one.

I have a table called 'payments' with the fields amount and currency, and i'm trying to display a summary totals table for each of the currencies. As an example:

<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>

In reality, I am using 12 currencies so I have 12 separate queries but it feels inefficient so I was wondering if there is an easier way to achieve the same result?

Many thanks!

SELECT currency,
       SUM(amount) as total
  FROM payments
 GROUP BY currency
     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); 
       } 
    }

You can use a GROUP BY here.

SELECT currency, SUM(amount) as total FROM payments GROUP BY currency

http://dev.mysql.com/doc/refman/5.1/en/group-by-modifiers.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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