[英]Insert records from one table to multiple relational tables using MySQL
我有三個表customer , 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
我不想只使用任何編程語言 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.