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!

3 Answers 3

3
SELECT currency,
       SUM(amount) as total
  FROM payments
 GROUP BY currency
Sign up to request clarification or add additional context in comments.

2 Comments

This is known as aggregate functions, mysqltutorial.org/mysql-aggregate-functions.aspx
Thanks Mark! and everyone else for your help. Group by worked a treat :)
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); 
       } 
    }

1 Comment

In your loop, you're using MySQLi, so you can use a prepared statement with a currency bind variable: using prepared statements isn't just a protection against SQL injection, but can help performance as MySQL doesn't need to parse the statement each time it executes (just the first time), so it's more efficient to use bind vars as well as more secure
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.