简体   繁体   中英

Copy record to another table when a field value changes

Consider 2 tables:

-- Table apples
id  |  randomstring  |  type TINYINT(1) DEFAULT 0

-- Table pears
id  |  randomstring | is_complete TINYINT(1) DEFAULT 0

Much like PHP events, is it possible to detect that when the field pears.is_complete is updated to a 1 from a 0, MySQL automatically copies the contents of pears.randomstring to apples.randomstring and sets the value of apples.type to 1?

If this is not possible in MySQL, can it be done in PHP where a php file is called when the value of a field changes?

If your running MySQL 5.0.2 or greater then using a trigger might be your best bet. Just create an update trigger that would run when the is_complete value changes to a 1.

Trigger code:

DELIMITER $$

CREATE TRIGGER `{database name}`.`{name of trigger}` 
  AFTER UPDATE ON `{database name}`.`pears`
FOR EACH ROW BEGIN
  IF(NEW.is_complete = 1) THEN
    # Add your random string to the apple table code
    INSERT INTO `{database name}`.`apples` (randomstring, type)
    VALUES (NEW.randomstring, 1);
  END IF;
END $$

DELIMITER;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM