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
IDinTABLE_2when they are changed inTABLE_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:
The above table structure will update all the matching
IDfromTABLE_2whenever anIDinTABLE_1is modified (ON UPDATE CASCADE). Also, whenever you delete anIDfromTABLE_1, all the matching entries fromTABLE_2will also be deleted (ON DELETE CASCADE). Because of this constraint, theIDfromTABLE_2has to exist inTABLE_1for anINSERTto 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.