+ Reply to Thread
Results 1 to 4 of 4

Thread: MySQL Total Column

  1. #1
    councils is offline x10Hosting Member councils is an unknown quantity at this point
    Join Date
    Jan 2010
    Posts
    1

    MySQL Total Column

    Hello,

    I could do with some help with a MySQL table.
    I've got one column for values. What I need is for each time a new row is added to run though that column, add up the existing values, then insert the result into the Total column in that row. Can anyone help?

    Thanks.

  2. #2
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: MySQL Total Column

    Since column totals are a property of the table and not whatever the rows represent, the total shouldn't be stored in rows of the table. Additionally, this redundancy will potentially cause inconsistencies, and it violates third normal form.

    Instead, use SUM or WITH ROLLUP in your queries to get the total. SUM is an aggregate function, which means to use it rows must be combined into a single row. If you want separate rows and a total, use WITH ROLLUP or a JOIN.

    Code:
    -- Note: including a non-aggregate, non-grouped column (`name` in this 
    -- example) as a selected column is non-standard SQL, but supported by MySQL. 
    -- It only works properly because the statement groups by a table key (here, `id`).
    SELECT id, name, SUM(amount) 
      FROM table
      GROUP BY id WITH ROLLUP;
    
    -- or
    
    SELECT SUM(t1.amount) 
      FROM table AS t1 
        JOIN table AS t2;
    If the above isn't performant enough, and the number of insertions, updates and deletions is likely to be low compared to the number of selections, you can create another table to hold statistics about the first table and use triggers to update the statistics table.

    Code:
    CREATE TABLE table_statistics (
        `name` VARCHAR(32),
        `column` VARCHAR(32),
        `stat` VARCHAR(16),
        `value` FLOAT -- if you also need to store statistics for non-numeric column types, use VARCHAR and store everything as strings
    );
    
    INSERT INTO table_statistics 
    (`name`, `column`, `stat`, `value`)
      SELECT 'table', 'amount', 'SUM', SUM(amount) FROM `table`;
    
    
    CREATE TRIGGER add_table_amount
    AFTER INSERT ON `table`
    FOR EACH ROW
    UPDATE table_statistics 
        SET value=value+NEW.amount 
        WHERE name='table' AND `column`='amount' AND `stat`='SUM';
    
    CREATE TRIGGER update_table_amount
    BEFORE UPDATE ON `table`
    FOR EACH ROW
    UPDATE table_statistics 
        SET value=value-OLD.amount +NEW.amount 
        WHERE name='table' AND `column`='amount' AND `stat`='SUM';
    
    CREATE TRIGGER delete_table_amount
    AFTER DELETE ON `table`
    FOR EACH ROW
    UPDATE table_statistics 
        SET value=value-OLD.amount 
        WHERE name='table' AND `column`='amount' AND `stat`='SUM';
    If you had posted sample code (a table creation statement, in this case), I could have shown you queries more relevant to your project. You should also describe the what you're trying to achieve with the column total. See the links in my sig for more on asking for help.
    Last edited by misson; 02-11-2011 at 06:22 PM.
    Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Eric Raymond's and Jon Skeet's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.
    Misson, not Mission.

  3. #3
    descalzo's Avatar
    descalzo is offline Grim Squeaker descalzo has a brilliant futuredescalzo has a brilliant futuredescalzo has a brilliant future
    Join Date
    Jul 2009
    Location
    Ankh-Morpork
    Posts
    7,636

    Re: MySQL Total Column

    Quote Originally Posted by misson View Post
    Since column totals are a property of the table and not whatever the rows represent, the total shouldn't be stored in rows of the table.
    And if the total is just meant to represent "total of values after this item was added"?

    The values in the column could change later, making that information impossible to reconstruct.
    Nothing is always absolutely so.

  4. #4
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: MySQL Total Column

    Quote Originally Posted by descalzo View Post
    And if the total is just meant to represent "total of values after this item was added"?
    In any case, it's not clear what councils wants, so we can only guess.

    Quote Originally Posted by descalzo View Post
    The values in the column could change later, making that information impossible to reconstruct.
    If councils wants a running total, changing earlier values is not an insignificant consistency problem. Note that "earlier" isn't well defined according to councils' post: would it refer to insertion order (as you posit), ordering by one of the table fields or by some property of whatever is being modeled which isn't represented in the table? Using views is the stablest approach for running totals; triggers would be problematic.
    Last edited by misson; 02-11-2011 at 08:07 PM.
    Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Eric Raymond's and Jon Skeet's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.
    Misson, not Mission.

+ Reply to Thread

Similar Threads

  1. MySQL error causing total site shutdown
    By kriztov in forum Free Hosting
    Replies: 0
    Last Post: 09-30-2010, 08:47 AM
  2. Problem with two column CSS layout and tables
    By gottaloveit in forum Graphics & Webdesign
    Replies: 1
    Last Post: 04-24-2008, 04:19 PM
  3. Mysql help needed: getting number of items in table column
    By xprtweb in forum Programming Help
    Replies: 1
    Last Post: 02-23-2008, 01:17 AM
  4. 3 column layout ideas.
    By lambada in forum Scripts & 3rd Party Apps
    Replies: 3
    Last Post: 04-06-2006, 11:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers