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;
答案 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中了解不同类型的外键约束。