2013-02-09 39 views
2

我想用INSERT ... ON DUPLICATE KEY UPDATE執行一點點複雜的upsert操作。但我無法實現它的工作。MySQL upsert with extra check

這是我想要做什麼:

  1. 嘗試插入一條記錄。如果插入成功,那很好。
  2. 如果該記錄存​​在,請更新記錄。
  3. 更新記錄時,如果check_status字段爲1,則保留說明和註釋字段。
  4. 更新記錄時,它的check_status字段爲0,然後更新描述和註釋字段。

之前寫出來的SQL,讓我們假設存在some_table有如下記載:

column name  | val 
-----------------+------------------------- 
some_unique_key | 32 
description  | existing description 
comment   | existing comment 
check_status  | 1 

所以爲了做到我上面描述的操作,我使用的SQL如下:

INSERT INTO some_table ('description', 'comment', 'some_unique_key') 
VALUES ('some description', 'some comment', 32) 
ON DUPLICATE KEY UPDATE 
description = IF(check_status = 1, VALUES(description), 'some description') 
comment = IF(check_status = 1, VALUES(comment), 'some comment') 

我認爲VALUES(描述)會給我數據庫表中現有記錄的值(即'現有描述')。但是,它似乎給了我想要插入的東西,即'一些描述'。

有沒有人知道如何正確使用SQL來做到這一點。嘗試插入時引用現有記錄中值的最佳方法是什麼?

回答

5

簡單。不要使用VALUES()(你已經在做了,指的是check_status現有的值):

INSERT INTO some_table ('description', 'comment', 'some_unique_key') 
VALUES ('some description', 'some comment', 32) 
ON DUPLICATE KEY UPDATE 
description = IF(check_status = 1, description, 'some description') 
comment = IF(check_status = 1, comment, 'some comment') 

或者用它來設置新的內容,而不是重複自己:

INSERT INTO some_table ('description', 'comment', 'some_unique_key') 
VALUES ('some description', 'some comment', 32) 
ON DUPLICATE KEY UPDATE 
description = IF(check_status = 1, description, VALUES(description)) 
comment = IF(check_status = 1, comment, VALUES(comment)) 
+0

哈哈。哎唷,就這麼簡單!謝謝你的回答@eggyal! – 2013-02-09 23:44:42

相關問題