一尘不染

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

sql

当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$$

阅读 146

收藏
2021-03-08

共1个答案

一尘不染

使用 <=>

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。抱歉,在发布问题之前应该已经阅读了手册,但希望对您有所帮助。

2021-03-08