简体   繁体   English

如何创建SQL Delete,它也会删除相关记录

[英]How do I create SQL Delete that will also delete related records

I have two tables in my mySQL database: INVOICE and INVOICE_LINE. 我的mySQL数据库中有两个表:INVOICE和INVOICE_LINE。 Both tables have a primary key column (auto-increment) ID. 两个表都有一个主键列(自动递增)ID。 INVOICE_LINE has a column INV_ID which is related to INVOICE.ID ie relationship was created by defining column INVOICE_LINE.INV_ID as foreign key to INVOICE.ID. INVOICE_LINE具有与INVOICE.ID相关的INV_ID列,即,通过将INVOICE_LINE.INV_ID列定义为INVOICE.ID的外键来创建关系。

How would I write an SQL for this? 我将如何为此编写SQL?

Method 1: 方法1:

Enforce foreign key constraints between these two tables INVOICE and INVOICE_LINE having ON DELETE CASCADE behavior. 在具有ON DELETE CASCADE行为的两个表INVOICEINVOICE_LINE之间强制执行外键约束。 Thus deleting an entry from INVOICE table will delete all the corresponding records in INVOICE_LINE table. 因此,从INVOICE表中删除条目将删除INVOICE_LINE表中的所有相应记录。

Method 2: 方法2:

If you don't have foreign key constraint between these two tables then you need to adopt the following query: 如果这两个表之间没有外键约束,则需要采用以下查询:

DELETE inv,inv_line
FROM INVOICE inv 
LEFT JOIN INVOICE_LINE inv_line ON inv.ID = inv_line.INV_ID
WHERE inv.ID = ?

Note: 注意:

I've used LEFT JOIN instead of INNER JOIN because if any invoice has no corresponding invoice line in INVOICE_LINE table then INNER JOIN won't delete the record from INVOICE table. 我使用了LEFT JOIN而不是INNER JOIN因为如果任何发票在INVOICE_LINE表中没有对应的发票行,那么INNER JOIN不会从INVOICE表中删除该记录。 But LEFT JOIN does 但是LEFT JOIN确实

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

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