本文介绍了mysql-自动更新另一个表中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表,一个用于存储用户的报告,另一个用于存储用户.

I have two tables, one for storing reports of a user, and another for storing users.

1. Report_table
-----report_id(P)-----user_id--------
        001           user1
        002           user1 
        003           user3


2.Users table 
-------user_id(P)-------no_of_reports
        user1             2
        user2             0
        user3             1 

现在,每当将报告插入report_table(例如report_id:004,user_id:user1)时,我都会像这样更新两个表.

Now whenever a report is inserted in report_table(say report_id:004, user_id: user1), I update both tables like this.

INSERT INTO reports_table VALUES (004,`user1`)
INSERT INTO users_table  (user_id,no_of_reports) VALUES (`user1`,1)
  ON DUPLICATE KEY UPDATE no_of_reports=no_of_reports+1;

是否有更好的方法来做到这一点.插入新报告时,是否可以自动递增 no_of_reports计数器?

Is there a better way of doing this.. Is there a way of automatically incrementing the no_of_reports counter when a new report is inserted?

推荐答案

您可以使用AFTER INSERT触发器

http://dev.mysql.com/doc/refman/5.0/en/triggers.html

这篇关于mysql-自动更新另一个表中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-20 22:23