简体   繁体   English

当删除同一表中的另一行时,将行内的部分/全部值更新为null

[英]Updating some/all value inside row to null when another row in same table is deleted MYSQL

I have a mysql table like below 我有一个如下的mysql表

id  tetangga1 tetangga2
1   null     null                       
2   1        3              
3   1        4           
4   4        5         
5   4        6         
6   6        null      

i need to update either tetangga row's value to NULL when one of the row inside the same table is deleted, in example, if i delete the row 1, then the table would look like this 当删除同一张表中的某一行时,我需要将任一tetangga行的值更新为NULL,例如,如果我删除第1行,则该表将如下所示

id  tetangga1 tetangga2                       
2   NULL        3              
3   NULL        4           
4   4           5         
5   4           6         
6   6           NULL  

explanation: row 1 will be deleted, row 2 and 3 tetangga1's value will be updated to null 说明:第1行将被删除,第2行和第3行tetangga1的值将更新为null

how can i achieve it? 我该如何实现?

You can do this with a foreign key relationship defined appropriately: 您可以使用适当定义的外键关系来执行此操作:

alter table t
    add constraint fk_t_tetangga1
        foreign key (tetangga1) references t(id)
        on delete set NULL;

This is actually better than a trigger. 这实际上比触发器更好。 The database will maintain the relational integrity. 数据库将保持关系的完整性。

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

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