mysql触发插入的空值
我想要一个特定字段的 mysql 触发器。当 NULL
值插入此字段时,我想将其替换为默认值。我知道这段代码不正确,但它会让您了解我想要什么。
CREATE TABLE IF NOT EXISTS example(
id INT NOT NULL AUTO_INCREMENT,
parent_id INT NOT NULL
);
CREATE TRIGGER insert_parentId_trigger BEFORE INSERT ON example
FOR EACH ROW BEGIN
IF parent_id = NULL THEN
SET parent_id = 0;
END IF
END;
I was wanting a mysql trigger for a specific field. When a NULL
value is inserted into this field I would like to replace it with a default value. I know this code is not correct, but it would give you an idea of what I want.
CREATE TABLE IF NOT EXISTS example(
id INT NOT NULL AUTO_INCREMENT,
parent_id INT NOT NULL
);
CREATE TRIGGER insert_parentId_trigger BEFORE INSERT ON example
FOR EACH ROW BEGIN
IF parent_id = NULL THEN
SET parent_id = 0;
END IF
END;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
not null default 0
声明该列,而不是稍后使用触发器。当 mysql 已经处理这种情况时,为什么我们需要在这里使用触发器?
您可以使用 alter 命令来更新列的定义
Declare that column with
not null default 0
instead of using trigger later.When mysql is already handling that condition why we need to use trigger here?
You can use alter command to update your definition of your column
我同意将 Null 简单地设置为 0 的示例,然后使用“默认值”就可以了,但是如果您想要一个可变且不能是默认值的值怎么办?例如:
对于这种类型的用例,或者需要查找的用例,您将无法使用默认值。
I agree with the example of a Null be simplistically set to 0, then using a "Default" is fine, but what if you're after a value that's variable and cannot be a Default? For example:
For this type of use case, or something that requires a lookup, you will not be able to use Default.
除了 Shakti Singh 对默认值完全正确之外,您还必须将
NULL
值与IS
进行比较,而不是=
它应该是
如果parent_id IS NULL
Besides that Shakti Singh is totally right with the default value, you have to compare
NULL
values withIS
instead of=
It should be
IF parent_id IS NULL