在插入某个表之前设置的MySQL触发器是否在我调用INSERT IGNORE并忽略插入时执行?
最佳答案
这是一个演示:
mysql> create table foo (foo_id int primary key);
mysql> create table bar (foo_id int);
mysql> create trigger foo_ins before insert on foo
for each row insert into bar set foo_id = new.foo_id;
mysql> insert ignore into foo set foo_id=123;
Query OK, 1 row affected (0.01 sec)
mysql> insert ignore into foo set foo_id=123;
Query OK, 0 rows affected, 1 warning (0.00 sec)
这应该只在 foo 表中插入一行,因为第二次尝试会与主键值冲突。我们看到第二次插入影响了 0 行,这意味着没有插入新行。
我们看看吧台上的效果是什么:
mysql> select * from bar;
+--------+
| foo_id |
+--------+
| 123 |
| 123 |
+--------+
插入了两行。这证明即使在执行插入忽略时也会触发触发器。
关于插入前使用 INSERT IGNORE 触发 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44692628/