I have a table that stores the summed values of a large table. I’m not calculating them on the fly as I need them frequently.
What is the best way to update these values?
-
I could delete the relevant rows from the table, do a full group by sum on all the relevant lines and then insert the new data.
-
Or I could index a timestamp column on the main table, and then only sum the latest values and add them to the existing data. This is complicated because some sums won’t exist so both an insert and an update query would need to run.
I realize that the answer depends on the particulars of the data, but what I want to know is if it is ever worth doing the second method; if there are millions of rows being summed in the first example and only tens in the second, would the second be significantly faster to execute?
You can try with triggers on update/delete. Then you check inserted or deleted value and according to it modify the sum in second table.
http://dev.mysql.com/doc/refman/5.0/en/triggers.html