如何使用 LAST_INSERT_ID() MySQL 进行多次插入


How to do a multiple insert using LAST_INSERT_ID() MySQL?

我有 3 个表:

  • 客户
  • 电子邮件
  • 电话

他们每个人都有自己的AUTO_INCREMENT id (id_customer, id_email, id_phone),我还有 2 个表格来关联它们:

  • customer_email
  • customer_phone

这些表包含其他表的表 ID 作为外键。

如何使用LAST_INSERT_ID()将它们关联到单个 SQL 语句中?或者你有什么建议?

您可以使用变量存储 LAST_INSERT_ID() 的结果。

INSERT INTO email(...) VALUES (...);
SET @email_id = LAST_INSERT_ID();
INSERT INTO phone(...) VALUES (...);
SET @phone_id = LAST_INSERT_ID();
INSERT INTO customer_phone(id_email, id_phone) VALUES(@email_id, @phone_id);