MySQL “After Insert” Trigger keeps inserting nulls

后端 未结 2 1031
礼貌的吻别
礼貌的吻别 2021-01-28 03:31

I really hope someone can help me out with this as it\'s been bugging me for days. I have an after insert trigger on my users table that inserts a record into an audit table aft

2条回答
  •  梦毁少年i
    2021-01-28 03:56

    Well, after creating different types of triggers and experimenting, i figured that the insert trigger might have been firing more than once for some reason, actually firing both insert and update triggers, and the last row always had nulls which was the only record being inserted. It's really strange. So anyway, to get around this i changed my code to this and it's working with no issues thus far:

    DELIMITER ^^
    
    CREATE TRIGGER UsersUpdate AFTER UPDATE ON users
    FOR EACH ROW
    BEGIN
    
    IF NEW.username IS NOT NULL THEN
    
    IF EXISTS (SELECT 1 FROM users_audit WHERE username = NEW.username) THEN
    UPDATE users_audit SET `username` = NEW.username,  `FirstName` = NEW.FirstName, `LastName` = NEW.LastName, `address` = NEW.address, `email` = NEW.email WHERE username = OLD.username;
    ELSE
    INSERT INTO users_audit (`username`, `FirstName`, `LastName`, `address`, `email`)
    VALUES (NEW.username, NEW.FirstName, NEW.LastName, NEW.address, NEW.email);
    END IF;
    
    END IF;
    
    END
    ^^
    

提交回复
热议问题