外键死锁问题

假设有表A和B,A主键id,B主键id,外键a_id。

insert into B (id, a_id) values (1, 1)
update A set datetime = 'xxx' where id = 1


insert into B (id, a_id) values (2, 1)
update A set datetime = 'xxx' where id = 1 

在多并发下会产生死锁

要避免问题,在insert 之前要先锁住 A表:

select * from A where id = 1 for update