Question

I've never implemented a trigger in MySQL but I now have a potential use for one and I'd like to know if it's possible.

In a nutshell, if data (a whole number) in a column in one table (table #1) is updated I need for multiple records which contain this data (the whole number) in a different table (table #2) to be updated as well, but only in the records which match the DATE of the record in the first table (table #1). No relationship (i.e. key) exists between these two tables because the data (the whole number) is not unique to either table.

Would a trigger be the best solution for this?

Was it helpful?

Solution

If I understand your logic correctly, this should be the trigger that you are looking for:

DELIMITER ;;

CREATE TRIGGER tbl1_upd BEFORE UPDATE ON tbl1
FOR EACH ROW
IF NOT (NEW.num <=> OLD.num) THEN 
  UPDATE tbl2 SET tbl2.num = NEW.num, updated='Y'
  WHERE tbl2.num = OLD.num AND tbl2.dt = NEW.dt;
END IF;;

DELIMITER ;

Please see an example here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top