由于声誉限制,这是this answer to a prior question的后续问题.我想知道在处理NULL值时是否有更有效的方法来测试每个字段的更改.
CREATE TABLE foo (
a INT NULL DEFAULT NULL,
b INT NULL DEFAULT NULL,
c INT NULL DEFAULT NULL
);
CREATE TABLE bar (
a INT NULL DEFAULT NULL,
b INT NULL DEFAULT NULL,
c INT NULL DEFAULT NULL
);
INSERT INTO foo (a, b) VALUES (1, 2);
我想要一个触发器,只有在更新更改了值时才会在更新后执行操作.所以这个UPDATE不会导致INSERT:
UPDATE foo SET a = 1 WHERE b = 2;
但是这个UPDATE将导致INSERT:
UPDATE foo SET a = 2 WHERE b = 2;
我已经编写了这个触发器来处理它,但是我希望可以简化IF语句.
DELIMITER ///
CREATE TRIGGER t_after_update_foo
AFTER UPDATE ON foo
FOR EACH ROW
BEGIN
IF
((OLD.a <> NEW.a OR OLD.a IS NULL OR NEW.a IS NULL) AND (NEW.a IS NOT NULL OR OLD.a IS NOT NULL))
OR
((OLD.b <> NEW.b OR OLD.b IS NULL OR NEW.b IS NULL) AND (NEW.b IS NOT NULL OR OLD.b IS NOT NULL))
OR
((OLD.c <> NEW.c OR OLD.c IS NULL OR NEW.c IS NULL) AND (NEW.c IS NOT NULL OR OLD.c IS NOT NULL))
THEN
INSERT INTO bar (a, b, c) VALUES (NEW.a, NEW.b, NEW.c);
END IF;
END;
///
DELIMITER ;
IF语句可以简化吗?或者是否有更简单的整体解决方案?
解决方法:
您可以使用coalesce(),它返回非空的第一个参数.
if coalesce(old.a,'') <> coalesce(new.a,'') or
coalesce(old.b,'') <> coalesce(new.b,'') or
coalesce(old.c,'') <> coalesce(new.c,'')
then
insert ...;
end if;
选择第二个参数可能很棘手.上面的示例适用于a,b和c是字符串以及空字符串值等于空值时的常见情况.
标签:sql,mysql,null,triggers
来源: https://codeday.me/bug/20190729/1569896.html