MySQL:在更新之前触发器也在插入时触发,为什么?

时间:2014-09-28 11:06:51

标签: mysql sql

我有三张桌子,A,B和C,其中A是B的父母,B是A的孩子。 C是B的历史。

下面是一个显示关系和多样性的图表(注意两个关系都在识别)。

0..*      1
B ------- A 
| 1 
| 
| 0..* 
C 

B的插入语句的格式为

insert into B ... on duplicate key update ... 

B中有一个触发器,在更新之前它将B上的当前行复制到C,即C包含B的历史记录。

当没有A时,上述工作很好。当添加A关系时,我发现触发器被触发两次,插入B和B上更新 - 为什么?

提前致谢。

更新 @Randy:这是简化的触发器代码:

USE `blah`;
DELIMITER $$
CREATE TRIGGER `B_BUPD` BEFORE UPDATE ON `B` FOR EACH ROW
BEGIN
    INSERT INTO C ( ... some values ... )
    VALUES ( now(), ... some old. values ... );
END

更新 @ron tornambe:这是表格的缩减SQL。我必须删除敏感信息和其他似乎不会影响此问题的表格,但希望它仍然有意义/有用。

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

CREATE SCHEMA IF NOT EXISTS `blah` DEFAULT CHARACTER SET utf8 ;
USE `blah` ;

-- -----------------------------------------------------
-- Table `blah`.`A`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `blah`.`A` (

  ...

  PRIMARY KEY (`mac_address`, `sensor_mac_address`),
  CONSTRAINT `fk_detector_sensor`
    FOREIGN KEY (`sensor_mac_address`)
    REFERENCES `blah`.`X` (`mac_address`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
ENGINE = InnoDB;


-- -----------------------------------------------------
-- Table `blah`.`B`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `blah`.`B` (

  ...

  PRIMARY KEY (`mac_address`),
  INDEX `fk_device_detector1_idx` (`detector_mac_address` ASC, `sensor_mac_address` ASC),
  CONSTRAINT `fk_device_detector1`
    FOREIGN KEY (`detector_mac_address` , `sensor_mac_address`)
    REFERENCES `blah`.`A` (`mac_address` , `sensor_mac_address`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;


-- -----------------------------------------------------
-- Table `blah`.`C`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `blah`.`C` (

  ...

  PRIMARY KEY (`time_date`, `mac_address`, `detector_mac_address`, `sensor_mac_address`),
  INDEX `fk_history_device1_idx` (`mac_address` ASC, `detector_mac_address` ASC, `sensor_mac_address` ASC),
  CONSTRAINT `fk_history_device1`
    FOREIGN KEY (`mac_address` , `detector_mac_address` , `sensor_mac_address`)
    REFERENCES `blah`.`device` (`mac_address` , `detector_mac_address` , `sensor_mac_address`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;


SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
DELIMITER $$
CREATE TRIGGER `B_BUPD` BEFORE UPDATE ON `B` FOR EACH ROW
BEGIN
    INSERT INTO C ( ... some values ... )
    VALUES ( now(), ... some old. values ... );
END$$

0 个答案:

没有答案