表的触发器可以应用于同一个表中的跟踪吗?

发布于 2024-08-27 19:30:03 字数 264 浏览 3 评论 0原文

表的触发器可以应用于同一个表中的跟踪吗?

也就是说,如果我有表说“employee”,现在我可以创建一个触发器,以便它跟踪同一“employee”表

触发器中的更改,例如

create trigger "<triggers_name>"  before insert on employee
For each row
Begin
 insert into employee field = timestamp;
end

Can a trigger for a table can be applied for tracking in same table?

That is IF I have table Say "employee" Now can i create a triggers such that it tracks the change in the same "employee" table

trigger such as

create trigger "<triggers_name>"  before insert on employee
For each row
Begin
 insert into employee field = timestamp;
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幸福%小乖 2024-09-03 19:30:03

简而言之,不。

那么让我们考虑一下这个问题。

“之前”触发器将在操作(在本例中为“插入”操作)发生之前执行。

如果这可行,并且每次在员工表上进行插入时都尝试向员工表中进行插入,那么您将在一个大的循环中永远循环递归混乱。

参考MySQL文档

“在存储的函数或触发器中,
不允许修改表
已经被使用(对于
读或写)通过声明
调用函数或触发器。”

请参阅此页面< 。


也就是说,如果您需要在插入时进行跟踪,我建议您使用第二个表,该表当然可以通过触发器引用,并为员工表创建一个 FK 并放置您的时间戳 该新表中的列并执行如下操作:

for each row
insert into employee_tracking (id, timestamp) on duplicate key update set timestamp = new_timestamp;

In short, no.

So let's think about this.

A "before" trigger will execute before the action (in this case, an "insert" action) takes place.

If this were to work, and you attempted to do an insert into the employee table every time an insert took place on the employee table, you'd loop forever in a big recursive mess.

Referenced from the MySQL docs

"Within a stored function or trigger,
it is not permitted to modify a table
that is already being used (for
reading or writing) by the statement
that invoked the function or trigger."

See this page for more info.


That said, if you need to do tracking when inserts take place, I would recommend using a second table which can certainly be referenced via a trigger. You and create a FK to the employee table and put your timestamp column in that new table and do something like this:

for each row
insert into employee_tracking (id, timestamp) on duplicate key update set timestamp = new_timestamp;
转瞬即逝 2024-09-03 19:30:03

如果您只想跟踪插入时间,可以将日期字段默认为 NOW()。

我想知道是否可以对刚刚插入的表进行更新?我理解第二次插入的递归,但也许您可以更新同一个表?

If you just wanted to track the insert time, you can have your datefield default to NOW().

I wonder if you can do an update on a table that was just inserted? The recursion I understand with the second insert but maybe you can update the same table?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文