简体   繁体   English

具有外键约束的多语句SQL删除

[英]Multi statement SQL delete with foreign key constraint

I'm using MySQL 5.5 with a complex schema that has foreign key constraints. 我正在使用具有外键约束的复杂模式的MySQL 5.5。

I want to execute multiple update and delete SQL statements. 我想执行多个updatedelete SQL语句。

After a subset of these statements have executed there may be foreign key constraint violations. 在执行了这些语句的子集之后,可能会违反外键约束。

After all of these statements have executed there shouldn't be foreign key constraint violations. 执行完所有这些语句后,就不应再违反外键约束。

I know about cascade , I don't want to use it because some of the changes require more complex logic. 我知道cascade ,我不想使用它,因为某些更改需要更复杂的逻辑。

My question is, is there a way to combine my multiple statements together (as a multi statement, transaction, etc) such that the foreign key constraints are not checked until after they are all completed? 我的问题是,是否有一种方法可以将我的多个语句组合在一起(作为一个多语句,事务等),以便直到它们全部完成后才检查外键约束? (And if there is an error than none of them are executed?) (如果出现错误,则不会执行任何错误?)

MySQL does not implement deferred constraint checking. MySQL不实现延迟约束检查。 From the manual, 从手册中

Deviation from SQL standards: Like MySQL in general, in an SQL statement that inserts, deletes, or updates many rows, InnoDB checks UNIQUE and FOREIGN KEY constraints row-by-row. 与SQL标准的偏差:通常,与MySQL一样,在插入,删除或更新许多行的SQL语句中,InnoDB逐行检查UNIQUE和FOREIGN KEY约束。 When performing foreign key checks, InnoDB sets shared row-level locks on child or parent records it has to look at. 在执行外键检查时,InnoDB在必须查看的子记录或父记录上设置共享的行级锁。 InnoDB checks foreign key constraints immediately; InnoDB立即检查外键约束; the check is not deferred to transaction commit. 该检查不会推迟到事务提交。 According to the SQL standard, the default behavior should be deferred checking. 根据SQL标准,默认行为应推迟检查。 That is, constraints are only checked after the entire SQL statement has been processed. 也就是说,仅在处理了整个SQL语句之后才检查约束。 Until InnoDB implements deferred constraint checking, some things will be impossible, such as deleting a record that refers to itself using a foreign key. 在InnoDB实现延迟约束检查之前,某些事情将是不可能的,例如删除使用外键引用其自身的记录。

So there is no way to check constraints only at the end of a group of SQL statements. 因此,无法仅在一组SQL语句的末尾检查约束。

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

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