MySQL在删除级联中,FK在源表中
我有两张桌子,客户和地址。客户具有FK引用表地址的列地址 桌上顾客MySQL在删除级联中,FK在源表中,mysql,Mysql,我有两张桌子,客户和地址。客户具有FK引用表地址的列地址 桌上顾客 create table customer ( id int(11) not null primary key, ... address int(11) null, constraint fk_customer_address foreign key (address) references address (id) on update cascade on
create table customer
(
id int(11) not null primary key,
...
address int(11) null,
constraint fk_customer_address
foreign key (address) references address (id)
on update cascade on delete cascade,
)
表地址
create table address
(
id int(11) not null primary key,
...
)
我希望在customer表中有address id,因为将来会有更多的表引用address表(Users.address、Business.address等),并且由于格式相同,所有地址都有一个表
当我删除customer表中的行时,address行保留在DB中
是否可以使用此FK关系删除地址表中的行,或者我必须手动(以编程方式)删除它
这是否意味着当我从地址中删除行时,客户行也会被删除
编辑:是的,确实如此。删除地址行时,您可能不希望删除客户行。我认为如果将fk定义为“on delete restrict”或“on delete set null”,则fk是正确的 因此,如果要删除地址记录:
➞ 对该地址的所有引用都将设置为null删除时设置null
➞ 您应该手动将所有子表上的地址id更新为其他值(或null),然后删除父行删除时限制
我将使用您的原始方法,使用“on delete set null”约束。“是否可以使用此FK关系删除地址表中的行”-否,这是否意味着当我从地址中删除行时,客户行也被删除了”-是的。如果我从客户中删除地址id,并在地址表中添加一些通用的“ref_id”,会有帮助吗?在地址中有客户id,并有一列用cid FKd向客户指示地址类型,这样当客户被删除时,所有地址都会被删除。但是,您需要编写代码以确保客户始终至少有一个地址。请注意,根据mysql版本的不同,MyIsam存储引擎上可能不会实现外键。请确保使用支持外键的存储引擎。当我删除customer表中的行时,address行保留在DB中。是否可以使用此FK关系删除地址表中的行,或者我必须手动(以编程方式)删除它?逻辑上不正确。假设存在另一行,该行引用相同的地址-
客户。地址
未定义为唯一。您可以从服务事件过程中删除“丢失”的地址。