mysql - 自动更新另一个表中的事件

2022-01-17 00:00:00 sql-update sql database mysql sql-insert

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

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触发器来处理TRIGGER

You can deal with TRIGGER by using a AFTER INSERT trigger

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

相关文章