I have a typical LAMP based site + Zend Framework where I have a base table and a summary table. Summary table is used to display data in reports.
Base table –
ID | Status
1 | 1
2 | 1
3 | 2
4 | 2
5 | 1
6 | 1
Summary table –
Status | Count
1 | 4
2 | 2
The base table will be changed(insert,update,delete) at an average of 20 times per day.
Currently, I am using triggers to call a stored procedure which will update the summary table based on the base table.
This is the stored procedure.
CREATE PROCEDURE UpdateSummary()
BEGIN
UPDATE summary a
INNER JOIN
(SELECT status, count(*) c from base group by status) b
ON a.status = b.status
SET a.count = b.c;
END
And I have 3 triggers (one for each – Insert, Delete and Update). I have shown the insert sample alone below. Other are similar to this.
CREATE TRIGGER S_T_TRIGGER_I
AFTER INSERT ON base
FOR EACH ROW
CALL UpdateSummary();
I want the summary table to be updated to the latest values always.
Using triggers and stored procedure like this is the best way or is there a elegant way to do this?
Why don’t you use a view like :
Each time you need, just do :
And you’ll get your result in real time (each call re-computed).
Views can be used the same way like table is used in Zend Framework. Just that you need to specify a primary key explicitly as explained here