当列的值从 null 变为 1 时,触发器不会运行

sim*_*dDB 4 mysql datatypes

我有这个触发器:

delimiter $$

create trigger tr 
after update on t1
for each row
begin

  if new.col1 !=old.col1 
    then update t2 set col2 =1 where t2.col3=t1.col3;
  end if;

end

$$
Run Code Online (Sandbox Code Playgroud)

此触发器在col1的值从 0 更改为 1 时起作用,但当其从 null 更改为 1 时,触发器不会在 中进行任何更改t2

我只是想知道为什么会这样。我知道 null 是不同的,但我只是比较这些值。

我已经解决了我的问题new.col1 =1

Phi*_*lᵀᴹ 7

将 if 条件更改为:

if (new.col1 != old.col1) or ( new.col1 is not null and old.col1 is null )
                          or ( old.col1 is not null and new.col1 is null )
Run Code Online (Sandbox Code Playgroud)

那应该可以解决您的问题。原始代码无法正常工作,因为您无法使用NULL值测试相等性- 您必须使用IS NULLIS NOT NULL

MySQL 还有一个“null-safe equals”运算符:<=>可以在这里使用它使上述条件更简单(并且仍然等效):

if not (new.col1 <=> old.col1)
Run Code Online (Sandbox Code Playgroud)