MySQL双路外键?

时间:2012-07-23 11:58:16

标签: mysql sql foreign-keys foreign-key-relationship

我想知道这种事情是否有效:

假设我有两张桌子:公司和地址。每家公司只能有一个地址。简化的架构看起来像这样。

COMPANIES
id
address_id
name
(...)

ADDRESSES
id
first_name
street
(...)

现在,我想在 COMPANIES.address_id - >上添加外键。 ADDRESSES.id ON UPETE UP NULL更新CASCADE 。 但我也希望在删除公司时删除该地址。所以另一种方式是 ADDRESSES.id - > COMPANIES.address_id ON DELETE CASCADE 。这样安全吗?

1 个答案:

答案 0 :(得分:2)

也许,使用触发器代替外键,可以解决您的问题。

create trigger addr_delete
after delete on companies for each row
begin
   delete from addresses where id=old.address_id
end