使用MySQL将记录从一个表插入到多个关系表

时间:2019-02-19 12:11:34

标签: mysql

我有三个表 customers customer_entity customer_info 。我想同时将客户表中的记录插入到customer_entity和customer_info中,但customer_entity表的主键将成为customer_info表的一部分。

假设代码可以写这样的东西吗?

INSERT INTO customer_entity (mobile, name)
INSERT INTO customer_info (customer_entity_id,email, name)
SELECT mobile, name, email customers FROM customers

enter image description here

我不想只使用任何编程语言MYSQL

2 个答案:

答案 0 :(得分:0)

此查询可能会对您有所帮助。

INSERT INTO customer_entity (mobile,email)
SELECT mobile, email FROM customer ORDER BY id ASC;
INSERT INTO customer_info (customer_entity_id, email)
SELECT customer_entity.id, email, (SELECT email FROM customer WHERE mobile= customer_entity.mobile) FROM customer;

这里 customer 表是已经有数据的主表,我们将其插入到 customer_entity 表和具有 customer_info 表中> customer_entity_id

答案 1 :(得分:0)

您还可以尝试使用SELECT LAST_INSERT_ID()

INSERT INTO customer_entity (mobile,email)
INSERT INTO customer_info (LAST_INSERT_ID(), email)

Docs

  

如果将记录插入到包含AUTO_INCREMENT的表中   列,您可以通过调用获取存储在该列中的值   mysql_insert_id()函数。