根据触发器和存储过程更新汇总表
我有一个典型的基于 LAMP 的站点 + Zend Framework,其中有一个基表和一个汇总表。汇总表用于显示报告中的数据。
基表 -
ID | Status
1 | 1
2 | 1
3 | 2
4 | 2
5 | 1
6 | 1
汇总表 -
Status | Count
1 | 4
2 | 2
基表平均每天会更改(插入、更新、删除)20 次。
目前,我正在使用触发器调用存储过程,该存储过程将根据基表更新汇总表。
这是存储过程。
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
我有 3 个触发器(每个触发器一个 - 插入、删除和更新)。我在下面单独展示了插入样本。其他的也与此类似。
CREATE TRIGGER S_T_TRIGGER_I
AFTER INSERT ON base
FOR EACH ROW
CALL UpdateSummary();
我希望汇总表始终更新为最新值。 使用像这样的触发器和存储过程是最好的方法,或者是否有一种优雅的方法来做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您正在一遍又一遍地重新查询数据库以获取您已经知道的数据。
为什么不只更新摘要并仅进行更改。
这会更快、更简洁、更优雅。
Well you are re-querying the DB over and over for data that you already know.
Why not just update the summary with only the changes.
This will be much much faster and more to the point much more elegant.
为什么不使用这样的视图:
每次需要时,只需执行:
您就会实时获得结果(每次调用都会重新计算)。
视图的使用方式与 Zend Framework 中使用表的方式相同。只是您需要按照解释明确指定主键 这里
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