MySQL offers the following:
INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1;
Does MySQL offer something similar for DELETE which would attempt to delete and upon foreign key constraint, update the record in the table which was attempted to be deleted?
For instance...
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;
If I understand correctly, you want a cascading foreign constraint on delete
and/or 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
);
This will delete the row in table2
when the corresponding row in table1
is deleted.
You can read about the different types of foreign key constraints in the documentation .
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.