2016-03-01 48 views
-1

我知道約ON DUPLICATE USE KEY條款。但我無法使用它,因爲我想在非唯一列上使用updateinsert更新列如果存在其他插入

我有table1table2。我想在table1上創建一個觸發器。

僞代碼:

IF id_code for corresponding id_name from table1 is present in table2 
then update record in table 2 
else record in table2. 

對於防爆。

table1 has column1 id_code, column2 id_name 
table2 has column1 id_code, column2 status 

IF id_code for corresponding id_name from table1 is present in table2 
UPDATE status column in table2. 
ELSE insert id-code in table2 
+0

請參考這個http://stackoverflow.com/questions/4205181/insert-into-a-mysql-table-or-update-if-exists –

+0

*「我想創建觸發器」* - 看一看在一些例子中:http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html – axiac

+0

創建一個觸發器,然後使用插入...在重複密鑰更新...內。 – Shadow

回答

0

最好的辦法可能是使用條件語句,因爲就像你說的,你正在檢查一個非唯一值,因此無法重複鍵使用:

IF EXISTS (SELECT id_code FROM table2 WHERE id_code = 'code from table1') THEN 
    UPDATE table2 SET status = 'new status' WHERE id_code = 'code from table1'; 
ELSE 
    INSERT INTO table2 (id_code, status) VALUES ('code from table1', 'new status'); 
END IF; 

唯一需要注意這裏是該控制結構僅在存儲過程中有效,因此您需要將其存儲在存儲過程或觸發器中。

+0

我想創建觸發器而不是SP, 我可以在觸發器中使用上面的代碼嗎? – Priyanshu

+0

是的,你也可以在觸發器中使用它。 – ElGavilan

相關問題