Python MySQL中的多表插入
我有四张桌子Python MySQL中的多表插入,python,mysql,sql,Python,Mysql,Sql,我有四张桌子 表a 表b 表c 表u abc 表a、表b、表c包含一个自动递增ID作为主键和一些任意列。 table_abc有三个外键,分别是table_a、table_b和table_c的ID 我想按如下方式进行插入(原子方式,即,如下所述全部插入1-4,或完全不插入): 插入表a 可能会在表_b中插入 可能会在表c中插入 分别使用插入1、2和3生成的ID插入表\u abc,如插入表\u abc(a\u ID、b\u ID、c\u ID)值([ID来自插入1]、[ID来自插入2或NULL]
- 表a
- 表b
- 表c
- 表u abc
插入表\u abc(a\u ID、b\u ID、c\u ID)值([ID来自插入1]、[ID来自插入2或NULL]、[ID来自插入3或NULL])
我正在使用Python和Pandas制作插入。当然,我希望在每次插入后将id存储在python变量中,但我觉得这会使事情变得复杂,因为我需要原子性。您使用
last\u insert\u id()
:
顺便说一句,我想你指的是last_insert_id(),不是last_insert_id,而是setselect@Lobs001 . . . 非常感谢。
insert into a ( . . . )
values ( . . . );
set @a_id = last_insert_id();
insert into b ( . . . )
values ( . . . );
set @b_id = last_insert_id();
insert into c ( . . . )
values ( . . . );
set @c_id = last_insert_id();
insert into abc(a_id, b_id, c_id)
values (@a_id, @b_id, @c_id);