繁体   English   中英

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

[英]Insert records from one table to multiple relational tables using MySQL

我有三个表customercustomer_entitycustomer_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

在此处输入图片说明

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

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

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

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

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

文档

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM