简体   繁体   中英

mysql foreign key update constraint in a transaction?

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?

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.

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.

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.

create table tableB (
  column_a char(2) primary key
);

create table tableA (
  column_a char(2) not null 
    references tableB (column_a) 
    on update cascade
    on delete cascade,
  column_b char(2) not null,
  primary key (column_a, column_b)
);

insert into tableB values ('aa');
insert into tableA values ('aa', 'bb');

update tableB 
set column_a = 'cc' 
where column_a = 'aa';

select *
from tableA;

column_a   column_b
--
cc         bb

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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