Here is the MYSQL Trigger that I have written:
DELIMITER //
CREATE TRIGGER updtrigger BEFORE UPDATE ON myTable
FOR EACH ROW
BEGIN
IF (OLD.column IS NOT NULL AND NEW.column IS NOT NULL AND NEW.column != OLD.column) THEN
SET NEW.col_updated_on = NOW();
END IF;
END //
DELIMITER ;
If column has a value (say, “movie”), and I update it to get new value, “movie,music”, the trigger gets executed and col_updated_on should have the current timestamp.
However, when column is NULL and I update it to get the new value, “movie”, the col_updated_on column will still show me the old timestamp.
Please let me know what change I must do to check for this condition as well.
Thanks in advance for your replies.
I have another question. Is the below pseudo possible??
Here are my two tables –
myTable(id, someId, col_updated_on);
myOtherTable(id, col1, col2);
myTable.someId has a 1-on-1 relation with myOtherTable.id
I want to update myTable.col_updated_on whenever myOtherTable.col1 and myOtherTable.col2 are updated. How do i do this? and should i use “BEFORE UPDATE” or “AFTER UPDATE”?
Use the
NULL-safe equality operator:However, note that MySQL’s
TIMESTAMPdata type can (and, by default, will) automatically update whenever a record is updated, making such a trigger unnecessary.But also, you REALLY shouldn’t store multiple items in a delimited string in a relational database like MySQL. Read up on database design, especially one-to-many relationships: one would fare much better by having a separate table, in which each record links an identifier (key) from your existing (foreign) table to a single item; one would then join the tables together as required in your queries.