Before / after insert trigger using auto increment field(使用自动增量字段插入触发器之前/之后)
问题描述
我遇到了一个应该修复表中列的插入触发器的问题:
I'm having troubles with an insert trigger that is supposed to fix a column in a table:
id - auto increment int
thread_id - int [NULL]
我想要实现的是将 thread_id
设置为 id
如果它作为 NULL 插入.我失败的原因是:
What I want to achieve is to set the thread_id
to id
if it's inserted as NULL. I have failed because:
- 使用
before insert
触发器仍然没有id
的新值并且神秘地将thread_id
设置为 0 - 使用
after insert - update
触发器抛出合理的异常无法更新表,因为它已被语句使用
. - 您不能添加额外的自增字段
- using
before insert
trigger still does not have the new value forid
and mysteriously setsthread_id
to 0 - using
after insert - update
trigger throws reasonable exceptioncan't update table because it is already used by the statement
. - you can not add additional auto increment field
这个问题的解决方案是什么?
What is the solution to this problem?
推荐答案
DELIMITER $$
CREATE TRIGGER mytrigger BEFORE INSERT ON yourtable
FOR EACH ROW BEGIN
SET NEW.thread_id = IF(ISNULL(NEW.thread_id), 0, NEW.thread_id);
END;
$$
Edit:为了修改当前记录的值,不使用UPDATE语句,使用NEW.columname
in order to modify values of the current record, you don't use UPDATE statement, you access them by using NEW.columname
这篇关于使用自动增量字段插入触发器之前/之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用自动增量字段插入触发器之前/之后


基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01