0

如果我有两个表 A 和 B 都带有插入触发器。

如果表 A 触发器向 B 中插入一行,然后执行更新 B 触发器何时触发?立即插入还是等待 A 触发器完成?

使用伪伪代码会是

A Trigger Starts
  A Trigger Inserts Row into B
  A Trigger Updates B
A Trigger Ends

B Trigger Fires (after insert)

或者

A Trigger Starts
  A Trigger Inserts Row into B
  B Trigger Fires (after insert)
  A Trigger Updates B
A Trigger Ends
4

1 回答 1

1

好吧,您可以使用带有这样的代码的日志表(general_log 不会帮助您)自己检查它

表架构

CREATE TABLE a (id INT);
CREATE TABLE b (id INT);
CREATE TABLE c (id INT);
DROP TABLE IF EXISTS tg_log;
CREATE TABLE tg_log 
(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, 
  dt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  message VARCHAR(512)
);

触发器

DROP TRIGGER IF EXISTS tg_a;
DELIMITER $$
CREATE TRIGGER tg_a
AFTER INSERT ON a
FOR EACH ROW
BEGIN
  INSERT INTO tg_log(message) VALUES('tg_a START');
  INSERT INTO b VALUES (NEW.id);
  INSERT INTO tg_log(message) VALUES('tg_a INSERT INTO b');
  UPDATE b SET id = id + 1 WHERE id = NEW.id;
  INSERT INTO tg_log(message) VALUES('tg_a UPDATE b');
  INSERT INTO tg_log(message) VALUES('tg_a END');
END$$
DELIMITER ;

DROP TRIGGER IF EXISTS tg_b;
DELIMITER $$  
CREATE TRIGGER tg_b
AFTER INSERT ON b
FOR EACH ROW
BEGIN
  INSERT INTO tg_log(message) VALUES('tg_b START');
  INSERT INTO c VALUES (NEW.id);
  INSERT INTO tg_log(message) VALUES('tg_b INSERT INTO c');
  INSERT INTO tg_log(message) VALUES('tg_b END');
END$$
DELIMITER ;

然后我们在表a中插入一行

INSERT INTO a VALUES(1);

这是我们在输出日志中看到的

+----+---------------------+--------+
| 编号 | dt | 留言 |
+----+---------------------+--------+
| 1 | 2013-07-27 23:31:42 | tg_a 开始 |
| 2 | 2013-07-27 23:31:42 | tg_b 开始 |
| 3 | 2013-07-27 23:31:42 | tg_b 插入 c |
| 4 | 2013-07-27 23:31:42 | tg_b 结束 |
| 5 | 2013-07-27 23:31:42 | tg_a 插入 b |
| 6 | 2013-07-27 23:31:42 | tg_a 更新 b |
| 7 | 2013-07-27 23:31:42 | tg_a 结束 |
+----+---------------------+--------+
一组 7 行(0.00 秒)

这是SQLFiddle演示

于 2013-07-28T03:42:24.577 回答