无法更新存储函数/触发器中的表“操作”,因为调用该存储函数/触发器的语句已使用该表

时间:2019-12-13 00:02:28

标签: mysql database triggers insert

给出一些字段定义为

的表操作
+--------------------------+-------------+------+-----+---------+----------------+
| Field                    | Type        | Null | Key | Default | Extra          |
+--------------------------+-------------+------+-----+---------+----------------+
| action_id                | int(11)     | NO   | PRI | NULL    | auto_increment |
| chat_id                  | int(11)     | YES  |     | NULL    |                |
| project_number           | bigint(20)  | YES  | MUL | NULL    |                |
| action_description       | text        | YES  |     | NULL    |                |

...

并将触发器定义为

DELIMITER $$
DROP TRIGGER IF EXISTS createActionChat;
CREATE TRIGGER createActionChat
AFTER INSERT ON action FOR EACH ROW 
BEGIN
        INSERT INTO chat (entity, entity_id) VALUES('action', NEW.action_id);
END $$
DELIMITER ; 

哪个尝试插入定义为的聊天表中

+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| chat_id   | int(11)     | NO   | PRI | NULL    | auto_increment |
| entity    | varchar(25) | NO   |     | NULL    |                |
| entity_id | int(11)     | NO   |     | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+

编辑:聊天中还有另一个触发器,插入后,该触发器会更新操作

DELIMITER $$
DROP TRIGGER IF EXISTS updateEntityChatId
CREATE TRIGGER updateEntityChatId
AFTER INSERT ON chat FOR EACH ROW 
BEGIN
        IF NEW.entity = 'action' THEN
                UPDATE action SET chat_id = NEW.chat_id where action_id = NEW.entity_id;     
        ELSEIF NEW.entity = 'issue' THEN
                UPDATE issue SET chat_id = NEW.chat_id where issue_id = NEW.entity_id;
        ELSEIF NEW.entity = 'risk' THEN
                UPDATE risk SET chat_id = NEW.chat_id where risk_id = NEW.entity_id;
        ELSEIF NEW.entity = 'benefit' THEN
                UPDATE benefit SET chat_id = NEW.chat_id where benefit_id = NEW.entity_id;
        END IF;
END $$
DELIMITER ;

添加此触发器并尝试使用简单的插入语句

insert into action(project_number, action_description) values(1111, 'this is a test for chat');

我收到以下错误

ERROR 1442 (HY000): Can't update table 'action' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

如果我删除createActionChat触发器,则插入会通过

编辑:如果我也删除了updateEntityChatId触发器(即具有任一触发器),则插入将通过

我看了其他几个类似的问题

并使用触发器将其插入另一个表中进行搜索,结果代码似乎与我自己的代码相同

任何帮助/建议将不胜感激

编辑:看来问题在于第二个触发器,即在插入聊天之后试图更新操作的updateEntityChatId导致了问题,有什么办法可以解决?

0 个答案:

没有答案