检测OLD值是否不等于NEW值且OLD值为NULL

时间:2013-04-10 14:11:40

标签: mysql sql triggers

当OLD值不等于NEW值时,我想在audit_field中插入一行。为此,我在每个插入之前添加了IF NEW.notes <> OLD.notes THEN。然而,我发现(我认为)如果OLD值为NULL,则不执行插入。我没有测试相反的情况是否正确,并且如果OLD值是某些东西并且NEW值为NULL,它将不会插入,但我希望它不会。

如何检测OLD值是否不等于NEW值且OLD值是否为NULL(或类似地,如果NEW值为NULL)?

CREATE TRIGGER tg_students_upd AFTER UPDATE ON students
FOR EACH ROW 
BEGIN
    IF NEW.name <> OLD.name OR NEW.ssn <> OLD.ssn OR NEW.notes <> OLD.notes THEN
        INSERT INTO audits(tableName,pk,task,dateChanged,users_id,dbUser,requesting_ip) VALUES ('students', @AID, 'u', NOW(), @users_id, USER(), @requesting_ip );
        SET @AID=LAST_INSERT_ID();
        IF NEW.name <> OLD.name THEN
            INSERT INTO audit_field(audits_id,columnName,oldValue,newValue) VALUES (@AID,'name',OLD.name,NEW.name);
        END IF;
        IF NEW.ssn <> OLD.ssn THEN
            INSERT INTO audit_field(audits_id,columnName,oldValue,newValue) VALUES (@AID,'ssn',OLD.ssn,NEW.ssn);
        END IF;
        IF NEW.notes <> OLD.notes THEN
            INSERT INTO audit_field(audits_id,columnName,oldValue,newValue) VALUES (@AID,'notes',OLD.notes,NEW.notes);
        END IF;
    END IF;
END$$

1 个答案:

答案 0 :(得分:4)

使用<=>

SELECT NOT 1 <=> 1,NOT NULL <=> NULL, NOT 1 <=> NULL, NOT 1 <=> 2, 1 <> 1, NULL <> NULL, 1 <> NULL, 1 <>2;

+-------------+-------------------+----------------+-------------+--------+--------------+-----------+-------+
| NOT 1 <=> 1 | NOT NULL <=> NULL | NOT 1 <=> NULL | NOT 1 <=> 2 | 1 <> 1 | NULL <> NULL | 1 <> NULL | 1 <>2 |
+-------------+-------------------+----------------+-------------+--------+--------------+-----------+-------+
|           0 |                 0 |              1 |           1 |      0 | NULL         | NULL      |     1 |
+-------------+-------------------+----------------+-------------+--------+--------------+-----------+-------+

PS。对不起,在发布问题之前应该阅读手册,但希望它能帮到别人。