【问题标题】:Multi-table inserts in MySQLMySQL中的多表插入
【发布时间】:2020-05-08 11:13:34
【问题描述】:

我有四张桌子

  • table_a
  • table_b
  • table_c
  • table_abc

table_a、table_b、table_c 包含一个自动递增的 ID 作为主键和一些任意列。 table_abc有三个外键,分别是table_a、table_b和table_c的ID。

我想做如下插入(原子地,即如下所述的全部 1-4,或者根本不插入):

  1. 在 table_a 中插入
  2. 可以在 table_b 中进行插入
  3. 可以在 table_c 中进行插入
  4. 分别使用插入 1,2 和 3 生成的 ID 插入 table_abc,如 INSERT INTO table_abc (a_id, b_id, c_id) VALUES ([id from insert 1], [id from insert 2 or NULL],[id from insert 3 or NULL] )

现在的问题是:如何获取插入 1,2 和 3 生成的 ID 值并将它们用于插入 4?请注意,每个表的 ID 都不相同,因此 a_id 可以为 45,而 b_id 为 10,c_id 为 2。

我正在使用 Python 和 Pandas 进行插入。我当然想在每次插入后将 ID 存储在 python 变量中,但我有一种感觉,因为我想要原子性,所以事情会变得复杂。

【问题讨论】:

    标签: python mysql sql


    【解决方案1】:

    你使用last_insert_id():

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

    【讨论】:

    • 顺便说一下,我假设您的意思是 last_insert_id(),而不是 last_insert_id,并设置而不是 select
    • @Lobs001 。 . .谢谢。
    猜你喜欢
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 2011-03-14
    相关资源
    最近更新 更多