CristiC
CristiC

Reputation: 22698

MySQL trigger - insert in another table only when data is different

I want to insert data in another table only when the data is different.
So for this I created a trigger on the first table, like this:

CREATE TRIGGER `RegistrationHistory` AFTER UPDATE ON `registration`
FOR EACH ROW
INSERT INTO registration_history (`Key`, `Name`, `Version`, `LastUpdate`)
SELECT OLD.Key, OLD.Name, OLD.Version, NOW()
WHERE OLD.Key != NEW.Key
AND OLD.Name != NEW.Name
AND OLD.Version != NEW.Version

The problem is that it errors out with:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE OLD.Key != NEW.Key

I noticed that if I try this doesn't work either:

SELECT 'ACBDE'
WHERE 1 = 1

So how should I insert into the history table using MySQL only when there is a difference?

Upvotes: 0

Views: 1759

Answers (1)

landons
landons

Reputation: 9547

Try wrapping in an if statement:

CREATE TRIGGER `RegistrationHistory` AFTER UPDATE ON `registration`
FOR EACH ROW BEGIN
  IF (NEW.Key != OLD.Key AND NEW.Name != OLD.Name AND NEW.Version != OLD.Version) Then
    INSERT INTO registration_history (`Key`, `Name`, `Version`, `LastUpdate`)
        VALUES(NEW.Key, NEW.Name, NEW.Version, NOW());
  END IF;
END

Upvotes: 1

Related Questions