2012-07-10 38 views
0

標題種類說這一切。SQL - 比較2個表格,然後將唯一的項目添加到第3個表格

我有2個表都相匹配的數據

Table Name: Customers 
_____________________________ 
ID | CompanyName 
-------------- 
1 | Joes 
2 | Kennys 
3 | Kellys 
4 | Ricks 
5 | Johns 


Table Name: OldCustomers 
_____________________________ 
ID | CompanyName 
-------------- 
1 | Joes 
2 | Kennys 
3 | Kellys 
4 | Ricks 

我想要做的兩個表之間的比較。然後取不表2中存在行,並把它添加到表我創建了名爲「NewCustomers」

+0

請註明您使用的是Oracle,SQL Server,MySQL的數據庫... – 2012-07-10 22:12:58

回答

2

您可以使用以下方法:

insert into NewCustomers(id, companyname) 
select c.id 
    , c.companyname 
from Customers c 
left join OldCustomers oc 
    on c.companyname = oc.companyname 
where oc.id is null; 

select * 
from NewCustomers 

SQL Fiddle with Demo

此查詢將查找OldCustomers表中缺少公司名稱的所有記錄。如果您想加入ID和公司名稱,您只需將and c.id = oc.id添加到left join即可。它會給你同樣的結果。

相關問題