Getting totals in MySQL

December 21st, 2005

At work recently, I had to grab the sum of totals from multiple rows meeting certain conditions in a mysql table. Rather than get each total and add them in PHP in a loop, I decided to get MySQL to do all the legwork for me:

SELECT sum(amount)
FROM table
WHERE id = '$id'
AND condition = '1'
GROUP BY id;

That should return you a summation of the amount columns for all rows matched in the the WHERE statemtents.


 Add to del.icio.us    Digg this    Technorati

Related Posts:

Entry Filed under: PHP, MySQL

1 Comment Add your own

  • 1. Andrew Johnstone  |  January 24th, 2006 at 9:37 pm

    Its surprising, how much logic you can actually push onto the database, and I recommend it when ever you can, providing it does not put extra overhead on something that maybe trivial on a server side language.

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

December 2005
M T W T F S S
« Nov   Jan »
 1234
567891011
12131415161718
19202122232425
262728293031  

Most Recent Posts