简体   繁体   English

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

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

I have three tables customers , customer_entity , customer_info .我有三个表customercustomer_entitycustomer_info I wanted to insert records from customers table to customer_entity and customer_info at same time, but customer_entity tables primary key will be part of customer_info table.我想同时将客户表中的记录插入到 customer_entity 和 customer_info 中,但是 customer_entity 表的主键将是 customer_info 表的一部分。

Assumed Code can we write something like this?假设代码我们可以写这样的东西吗?

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

在此处输入图片说明

I dont want to use any programming language only MYSQL我不想只使用任何编程语言 MYSQL

This query may help you.此查询可能对您有所帮助。

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;

Here the customer table is the main table which has data already and we are inserting it into customer_entity table and customer_info table with customer_entity_id .这里的customer表是已经有数据的主表,我们将它插入customer_entity表和customer_info表中的customer_entity_id

You can try using SELECT LAST_INSERT_ID() also:您也可以尝试使用SELECT LAST_INSERT_ID()

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

Docs 文档

If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.如果将记录插入包含 AUTO_INCREMENT 列的表中,则可以通过调用 mysql_insert_id() 函数获取存储在该列中的值。

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

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