在外键约束更新时删除

时间:2017-03-17 10:41:42

标签: mysql

MySQL提供以下内容:

INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;

MySQL是否为DELETE提供了类似的东西,它会尝试删除外键约束,更新表中试图删除的记录?

例如......

DELETE FROM table1 WHERE idtable1 = 123;
IF(foreign key constraint) {  //pseudo code...
  UPDATE table1 SET deleted=1 WHERE idtable1 = 123;
}

CREATE TABLE IF NOT EXISTS table1 (
  idtable1 INT NOT NULL,
  data VARCHAR(45) NULL,
  deleted TINYINT NOT NULL DEFAULT 0,
  PRIMARY KEY (idtable1))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS table2 (
  idtable2 INT NOT NULL,
  table1_idtable1 INT NOT NULL,
  data VARCHAR(45) NULL,
  INDEX fk_table2_table1_idx (table1_idtable1 ASC),
  CONSTRAINT fk_table2_table1
    FOREIGN KEY (table1_idtable1)
    REFERENCES table1 (idtable1)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要delete和/或update上的级联外部约束:

CREATE TABLE IF NOT EXISTS table2 (
  idtable2 INT NOT NULL,
  table1_idtable1 INT NOT NULL,
  data VARCHAR(45) NULL,
  INDEX fk_table2_table1_idx (table1_idtable1 ASC),
  CONSTRAINT fk_table2_table1
    FOREIGN KEY (table1_idtable1)
    REFERENCES table1 (idtable1)
    ON DELETE CASCADE
    ON UPDATE CASCADE
);

table2中的相应行被删除时,这将删除table1中的行。

您可以在documentation中了解不同类型的外键约束。