[英]How to insert unique records from one table to another in MySQL
我有一個示例表table1
:
id transaction_number net_amount category type
1 100000 2000 A ZA
2 100001 4000 A ZA
3 100002 6000 B ZB
我有一個示例表table2
:
id transaction_number net_amount category type
1 100002 6000 B ZB
如何插入不在table2
中但存在於table1
中的唯一記錄?
期望的結果:
id transaction_number net_amount category type
1 100002 6000 B ZB
2 100000 2000 A ZA
3 100001 4000 A ZB
INSERT INTO table2 ( transaction_number, net_amount, category, type )
(
/* Rows in table1 that don't exist in table2: */
SELECT ( table1.transaction_number, table1.net_amount, table1.category, table1.type )
FROM table1
LEFT JOIN table2 ON ( table1.transaction_number = table2.transaction_number )
WHERE table2.transaction_number IS NULL
)
嘗試這個
INSERT INTO table2 (transaction_number,net_amount,category,type)
(SELECT transaction_number,net_amount,category,type from table1) ON DUPLICATE KEY UPDATE
net_amount=VALUES(net_amount),category=VALUES(category),type=VALUES(type);
Usw not exists
如下:
Insert into table2
Select t1.*
From table1 t1
Where not exists
(Select 1 from table2 t2
Where t1.transaction_number = t2.transaction_number)
如果您不想在table2
中重復事務編號,請在該列(或您希望唯一的列)上創建唯一索引或約束。 讓數據庫處理數據的完整性:
alter table table2 add constraint unq_table2_transaction_number
unique (transaction_number);
然后使用虛擬更新on duplicate key update
更新:
insert into table2 (transaction_number, net_amount, category, type)
select transaction_number, net_amount, category, type
from table1
on duplicate key update transaction_number = values(transaction_number);
為什么我推薦這種方法? 首先,它是線程安全的,因此即使在多個查詢同時修改數據庫時也能正常工作。 其次,它讓數據庫負責數據完整性,因此無論事務如何更改,事務都是唯一的。
請注意,最新版本的 MySQL 已棄用此語法以支持(標准) on conflict
條款。 功能相似,但我認為這些版本並不普遍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.