简体   繁体   中英

MySQL Insert with value from previous row / MySQL triggers fire multiple times, how to limit them

I've created a log trigger that runs every time my other table is being updated, it creates a row with log informations. Unfortunately the system I am working on performs one operation as multiple queries so my trigger is fired much more times than I need. This is an output from one operation.

存储触发器输出的表

During parameter update the system firstly perform separate DELETE query for each row with matched parameter and product_id and then perform INSERT statement for every parameter that match product_id. Because of that the trigger is fired for every query with parameter (7 times per INSERT in this product, but there are cases with 100+ parameters per product)

So, I want to reduce it to one row per operation, the last row. In the future parameters will be updated by Webservice API so I am looking for a simpler solution than making events with JS and PHP. I thought about subtracting NOW() with the date from previous row (with the same product_id) and if the result is slightly different or the same I delete the previous row. I saw posts and articles with lag() but it seems that it's not working with INSERT INTO queries. If you have any suggestion, please, help

https://dev.mysql.com/doc/refman/8.0/en/faqs-triggers.html#faq-mysql-have-trigger-levels says:

Does MySQL 8.0 have statement-level or row-level triggers?

In MySQL 8.0, all triggers are FOR EACH ROW ; that is, the trigger is activated for each row that is inserted, updated, or deleted. MySQL 8.0 does not support triggers using FOR EACH STATEMENT .

It doesn't seem like a trigger of the type MySQL supports can work easily for your case. I recommend you simply execute your inserts, then execute the deletions you want to do from your application, not from triggers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM