【问题标题】:Multiple insert with last_insert_id in a transaction在事务中使用 last_insert_id 多次插入
【发布时间】:2024-01-22 10:40:01
【问题描述】:

我有一系列记录要插入到数据库中,但是数据库的结构需要特殊的方法:

BEGIN;
table contact -> firstname,lastname
table company -> name
table contact_company_vs -> contact_id,company_id (THESE TWO ARE LAST_INSERT_IDs FROM first two inserts)
COMMIT;

如何做到这一点?我是否应该通过一个接一个地进行一些插入来限制自己存储变量的 php 功能?

【问题讨论】:

    标签: php mysql insert transactions


    【解决方案1】:

    其实你可以用 php 或 sql 做到这一点

    PHP

    1. 使用 mysqli/pdo 和 innodb 表
    2. 将自动提交设置为关闭
    3. insert 1 -> 保存 $id(你可以通过 mysqli_insert_id 获取它,它会在事务中正常工作)
    4. 插入 2 -> 保存 $id2
    5. 插入 3 -> 你有 $id 和 $id2
    6. 提交所有更改
    7. 如果逻辑过程中有任何错误 - 回滚它们

    SQL

    我更喜欢使用存储过程:

    declare id1 bigint default 0;
    declare id2 bigint default 0;
    insert1 ... ;
    SELECT LAST_INSERT_ID() into id1;
    insert2 ... ;
    SELECT LAST_INSERT_ID() into id2;
    insert into contact_company_vs values(id1, id2);
    select id1, id2;
    

    这样的存储过程甚至会将两个生成的 id 返回到您的逻辑中

    【讨论】: