2

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

1 回答 1

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。抱歉,在发布问题之前应该阅读手册,但希望它会对其他人有所帮助。

于 2013-04-10T14:19:30.867 回答