Is it possible to update like this?
I have three tables. Tab_1,Tab_2 and Tab_3. Here Tab_2 and Tab_3 are depend on Tab_1. Means PK_t1 of Tab_1 is FK(Foreign Key) in the remaining tables.
Now I come to know that I have to update the PK_t1(Primary Key) column. If I update primary key column then FK column of the child tables(Tabl_2 and Tab_3) also should update.
---------------------------------------------
Example
Tab_1
ID(PK)| Cal2 |
---------------|
101 | abc |
102 | acw |
103 | bhj |
Tab_2
----------------
Address| Cal2(FK_ID)
----------------
ljjkkl | 103
ghhj | 101
dfgjdl | 101
Tab_3
----------------
Cal1 | ID(FK_ID)
----------------
n233b | 101
g55hhj | 103
d867hh | 102
And now If I wan to update the tablee Tab_1 as
开发者_高级运维Tab_1
ID(PK)| Cal2 |
---------------|
951 | abc |
952 | acw |
953 | bhj |
Will this(updation) cause to the child tables also.
Is it possible? Or what necessary actions I should take to achieve this.
Thanks in advance...!
This is one of the reasons for Cascade Update on foreign key relationships. With that, you would be able to update the PK in Table1 and it would automatically propagate to its child tables. That constraint would look something like:
Alter Table Table2
Add Foreign Key ( FK_ID )
References Table1( Id )
On Update Cascade
Without Cascade Update enabled, you have two choices:
- Disable all foreign key constraints, update the PK in Table1, update the child tables and then recreate the foreign key constraints.
- Add a new value into Table1 with the ID you want and run an Update on the child tables. For example, if you wanted to change the PK value 101 to 951:
Begin Transaction
Insert Table1( Id, Cal2 )
Values( 951, 'Foo' )
Update Table2
Set FK_ID = 951
Where FK_ID = 101
Update Table3
Set FK_ID = 951
Where FK_ID = 101
...
Delete Table1 Where Id = 101
Commit Transaction
The catch with this second approach is that none of the new ID values can collide with existing PK values.
Use database engine innodb and create table with option on update
, on delete
Refer here for foreign key constraints
精彩评论