简体   繁体   English

用外键从表中删除

[英]Delete from table with foreign key

Morning, 早上,

I have three tables: 我有三个表:

Table: debtors 表:债务人

id           -    INT(11)
type         -    ENUM('c', 'p')

Table: companies 表:公司

id           -    INT(11)
debtor_id    -    INT(11)
and a lot of other fields for companies

Table: private_individuals 表格:private_individuals

id           -    INT(11)
debtor_id    -    INT(11)
and a lot of other fields for private individuals

Foreign KEY SQL for companies(same is used for private individuals): 公司的外键SQL(私人使用相同):

INDEX `fk_private_individual_debtors1` (`debtor_id` ASC) ,
  CONSTRAINT `fk_private_individual_debtors1`
    FOREIGN KEY (`debtor_id` )
    REFERENCES `application_user`.`debtors` (`id` )
    ON DELETE CASCADE
    ON UPDATE NO ACTION)

When I delete a company or private individual I want the debtor to be deleted as well and it should work the other way around aswell(delete a debtor and the company or private individual is deleted aswell). 当我删除公司或个人时,我也希望债务人也被删除,并且它也应该以其他方式工作(删除债务人,公司或个人也将被删除)。

I'm thinking to do this with a trigger but I suppose there is a better way to do it.. 我正在考虑使用触发器来执行此操作,但我想有一种更好的方法来执行此操作。

Can anyone help please? 有人可以帮忙吗?

Delete a debtor and the company or private individual is deleted as well: 删除债务人,公司或个人也将被删除:

This can be done by ON DELETE CASCADE . 这可以通过ON DELETE CASCADE You specify this when you define the foreign key, and applies to all deletes on the table. 您在定义外键时指定此选项,并将其应用于表上的所有删除。 You cannot mention this at the indivudual DELETE level. 您不能在个别DELETE级别提及此。 See FOREIGN KEY Constraints in the MySql manual Remember this is dangerous in most cases and you are better off having this logic in your application code. 请参阅MySql手册中的FOREIGN KEY约束 。请记住,在大多数情况下,这是危险的,最好在应用程序代码中使用此逻辑。

When I delete a company or private individual I want the debtor to be deleted as well 当我删除公司或个人时,我也希望删除债务人

This is not directly possible. 这不是直接可能的。 You have built a foreign key relationship between a company and a debtor but there can be more than one company associated to the debtor. 您已经在一家公司和债务人之间建立了外键关系,但是与该债务人关联的公司可能不止一个。 There is nothing in the foreign key that prevents this. 外键中没有任何东西可以阻止这种情况。 You may have additional application logic (in a procedure, in your java/C# code, in triggers) but there is nothing in the foreign key level at all. 您可能具有其他应用程序逻辑(在过程中,在Java / C#代码中,在触发器中),但外键级别完全没有。 So since this is acheived by additional application logic your deletion also will need additional application logic. 因此,由于这是通过其他应用程序逻辑实现的,因此删除操作也将需要其他应用程序逻辑。 One another point to note is: you should delete a [arent only if all of its child records are deleted. 需要注意的另一点是:[仅当删除所有子记录时,才应删除它。

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

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