I have two tables, TABLE_1
and TABLE_2
.
TABLE_1
contains ID
and NAME
, where ID
is a primary key.
TABLE_2
contains ID
and DATA
, where ID
and DATA
form a compound primary key.
I'm looking for a SQL query that updates the ID
in TABLE_2
when they are changed in TABLE_1
.
How can I create this table structure?
TABLE_1
ID NAME
100 LLL
101 KKK
102 JJJ
TABLE_2
ID DATA
100 HHHHHHH
100 MMMMMMM
100 ZZZZZZZ
101 IIIIIII
101 FFFFFFF
102 EEEEEEE
Thank you for your help.
Not sure why you need to do this, but anyway.
One way to do this is to use foreign key constraints , available in the InnoDB storage engine:
CREATE TABLE `TABLE_1` (
`ID` int NOT NULL,
`NAME` varchar(255) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB;
CREATE TABLE `TABLE_2` (
`ID` int(11) NOT NULL,
`DATA` varchar(255) NOT NULL,
PRIMARY KEY (`ID`,`DATA`),
CONSTRAINT `FK_ID` FOREIGN KEY (`ID`)
REFERENCES `TABLE_1` (`ID`)
ON UPDATE CASCADE
ON DELETE CASCADE
) ENGINE=InnoDB;
The above table structure will update all the matching ID
from TABLE_2
whenever an ID
in TABLE_1
is modified ( ON UPDATE CASCADE
). Also, whenever you delete an ID
from TABLE_1
, all the matching entries from TABLE_2
will also be deleted ( ON DELETE CASCADE
). Because of this constraint, the ID
from TABLE_2
has to exist in TABLE_1
for an INSERT
to complete successfully.
Also keep in mind that foreign keys affect performance, but without knowing exactly why you want such a thing, I cannot suggest any better solution.
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.