I am posting this solution because it was hard for me to find what I needed. This post got me close enough (+1 thanks for that), and here is the final solution for reordering the column data before inserting if the data matches the test .
Note: this is from a legacy project inherited from where:
- The unique key is the
rridprefix + rrid - Before I took part, there were no restrictions preventing duplication of unique keys
- We needed to combine two tables (one of the duplicates) into the main table, which now has a restriction on the composite key (therefore, the merge is not performed because the win table will not allow duplicate data from an unclean table)
on duplicate key less than ideal because the columns are too numerous and can change
In any case, here is a trigger that puts any duplicate keys in the old column, allowing us to store obsolete, bad data (rather than run compound tablets with accumulation, a unique key) .. p>
BEGIN -- prevent duplicate composite keys when merging in archive to main SET @EXIST_COMPOSITE_KEY = (SELECT count(*) FROM patientrecords where rridprefix = NEW.rridprefix and rrid = NEW.rrid); -- if the composite key to be introduced during merge exists, rearrange the data for insert IF @EXIST_COMPOSITE_KEY > 0 THEN -- set the incoming column data this way (if composite key exists) -- the legacy duplicate rrid field will help us keep the bad data SET NEW.legacyduperrid = NEW.rrid; -- allow the following block to set the new rrid appropriately SET NEW.rrid = null; END IF; -- legacy code tried set the rrid (race condition), now the db does it SET NEW.rrid = ( SELECT if(NEW.rrid is null and NEW.legacyduperrid is null, IFNULL(MAX(rrid), 0) + 1, NEW.rrid) FROM patientrecords WHERE rridprefix = NEW.rridprefix ); END
WEBjuju Dec 20 '16 at 15:42 2016-12-20 15:42
source share