简体   繁体   English

可以这样更新吗?

[英]Is it possible to update like this?

I have three tables.我有三张桌子。 Tab_1,Tab_2 and Tab_3. Tab_1、Tab_2 和 Tab_3。 Here Tab_2 and Tab_3 are depend on Tab_1.这里 Tab_2 和 Tab_3 依赖于 Tab_1。 Means PK_t1 of Tab_1 is FK(Foreign Key) in the remaining tables.表示 Tab_1 的 PK_t1 是其余表中的 FK(Foreign Key)。

Now I come to know that I have to update the PK_t1(Primary Key) column.现在我知道我必须更新 PK_t1(Primary Key) 列。 If I update primary key column then FK column of the child tables(Tabl_2 and Tab_3) also should update.如果我更新主键列,则子表(Tabl_2 和 Tab_3)的 FK 列也应该更新。

---------------------------------------------
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 更新为

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...!提前致谢...!

Use database engine innodb and create table with option on update , on delete使用数据库引擎innodb并使用on update选项创建表, on delete

Refer here forforeign key constraints请参阅此处了解外键约束

This is one of the reasons for Cascade Update on foreign key relationships.这也是 Cascade Update 对外键关系的原因之一。 With that, you would be able to update the PK in Table1 and it would automatically propagate to its child tables.这样,您将能够更新 Table1 中的 PK,它会自动传播到其子表。 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:如果未启用级联更新,您有两种选择:

  1. Disable all foreign key constraints, update the PK in Table1, update the child tables and then recreate the foreign key constraints.禁用所有外键约束,更新 Table1 中的 PK,更新子表,然后重新创建外键约束。
  2. Add a new value into Table1 with the ID you want and run an Update on the child tables.使用您想要的 ID 在 Table1 中添加一个新值,并在子表上运行更新。 For example, if you wanted to change the PK value 101 to 951:例如,如果您想将 PK 值 101 更改为 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.第二种方法的问题是没有一个新的 ID 值可以与现有的 PK 值冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM