mysql事务中的外键更新约束?
我找不到关于此的官方 mysql 解释,所以我想把它放在这里。 如果我在 MySQL 中的两个表之间有外键约束,假设 tableA 是父表,tableB 是子表。并且,在父表A上,我将使用“ON UPDATE CASCADE ON DELETE CASCADE”来确保MySQL可以自动将更新/删除操作应用于子表B。
现在,我的问题是:子表和父表的更新是否在事务中? 或者使用下面的语句,有什么区别吗?
方法一: UPDATE tableA SET col1 =“A”和col2 =“B”;
方法二: 开始; UPDATE tableA SET col1 =“A”和col2 =“B”; 犯罪;
现在,我遇到了方法1中的问题:当表A更新时,表B可能需要很长时间才能更新其相应的列(当然不是在事务中)。 以前有人遇到过类似的问题吗?
I can not find official mysql explanation about this, so I wanna throw it here.
If I have foreign key constrains between two tables in MySQL, say tableA is the parent table, tableB is the child table. And, on parent tableA, I will use "ON UPDATE CASCADE ON DELETE CASCADE" to make sure actions of update/delete can be applied to child tableB by MySQL automatically.
Now, my question is: if the update to child table and parent table is in a transaction or not?
Or by using the following statements, any differences?
Method 1:
UPDATE tableA SET col1="A" and col2="B";
Method 2:
Begin;
UPDATE tableA SET col1="A" and col2="B";
Commit;
Now, I met the problems in method1: when tableA is updated, tableB might take very long to update its corresponding columns(not in a transaction for sure).
Anyone met similar problems before?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您的所有表都使用 InnoDB,那么您在事务中执行的几乎所有操作都包含在该事务中并且可以回滚。有些东西,比如 DROP TABLE 会进行隐式提交。但对于 select/update/insert/delete 来说,这一切都涵盖了。
这包括由外键级联关系触发的任何插入/更新/删除。
Assuming all of your tables are using InnoDB, then almost all actions you do while in a transaction are covered by that transaction and can be rolled back. Somethings, like
DROP TABLE
do an implicit commit. But for select/update/insert/delete, it's all covered.That includes any inserts/updates/deletes that are triggered by a foreign key cascade relationship.
如果 tableA 具有 ON UPDATE CASCADE ON DELETE CASCADE ,则 tableA 是“子”,而不是“父”。 (SQL 不使用术语“父”和“子”;tableA 是引用表,tableB 是引用表。)对引用列的更改tableB 将自动应用于 tableA 中的匹配值。
由于外键引用而级联的更新是单个事务。 SQL 必须以这种方式工作。如果更新是两个事务(一个用于引用表,一个用于引用表),并且对引用表的更新失败,则会使数据库处于不一致状态。 (例如,在上面的更新中,因为“aa”在 tableB 中会更改为“cc”,但在 tableA 中不会更改。dbms 不能让这种情况发生。)
If tableA has
ON UPDATE CASCADE ON DELETE CASCADE
, then tableA is the "child", not the "parent". (SQL doesn't use the terms "parent" and "child"; tableA is the referencing table, and tableB is the referenced table.) Changes to the referenced column in tableB will automatically be applied to matching values in tableA.An update that cascades because of foreign key references is a single transaction. SQL has to work that way. If the update were two transactions--one for the referenced table and one for the referencing table--and the update to the referencing table failed, it would leave the database in an inconsistent state. (For example, in the update above, because 'aa' would have changed to 'cc' in tableB, but not in tableA. The dbms can't let that happen.)