2017-03-22 80 views
-3

其實我需要在比較兩個mysql表與多列時更新mysql記錄,如果記錄不存在,它應該插入一個新的記錄。我怎樣才能實現它?以下是我的情況。由於事先如何通過比較多列來更新mysql記錄

表1:

Name | Age | occupation | DOJ | Salary | 
---------------------------------------------------------------- 
Raju | 27 | Manager | 12/12/12 | 12,000 
-------------------------------------- 
Raman | 30 | Director | 11/11/11 | 14,000 
- 
Sriram | 25 | Assistant | 10/10/10 | 10,000 
- 

表2:

Name | Age | occupation | DOJ | Salary | 
---------------------------------------------------------------- 
Raju | 27 | Manager | 12/12/12 | 12,000 
-------------------------------------- 
Raman | 30 | Director | 8/8/8 | 18,000 
- 
Ravi | 34 | CEO | 9/9/9 | 30,000 
- 

我有一個excel與一堆具有上述結構的記錄,我需要在臨時表中上載的記錄(temp_table),然後將該表與main表(main_table)進行比較,以確定是否有任何記錄存在或不存在,如果存在任何更新,則需要在Main_table上執行該更新,否則將其作爲新的插入到main_table中。

謝謝。

+0

您需要在Table 1和Table上的姓名,年齡,職業,司法部和工資創建唯一索引。然後,你可以「全天插入table1中的table1 select *」。或者'如果你想更新東西,則替換爲table2中的select *。 – Dimi

+0

你的問題不是很清楚。你將在哪裏插入?,你會在哪裏更新?爲什麼拉曼表1與拉曼表2不同?向我們展示數據庫模式,樣本數據和預期輸出。 \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是一個偉大的地方[** START **] (http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)來了解如何提高您的問題質量並獲得更好的答案。 –

+4

[Insert into MySQL table or update if exists](可能存在重複)(http://stackoverflow.com/questions/4205181/insert-into-a-mysql-table-or-update-if-exists) –

回答

1

當且僅當給定Name存在時,您可以編寫一個將返回1的選擇。然後你可以使用這個作爲另一個選擇的子查詢,否定存在,找到應該插入的內容。最後,你可以使用第二個選擇的insert - select

insert into Table2(Name, Age, Occupation, Doj, Salary) 
select Name, Age, Occupation, Doj, Salary 
from Table1 t2 where not exists (select 1 
           from Table2 t 
           where t.Name = t2.Name)