我想使用INSERT … ON DUPLICATE KEY UPDATE进行一些复杂的upsert操作.但我无法让它发挥作用.
这就是我想做的事情:
>尝试插入记录.如果插入成功,那很好.
>如果该记录存??在,请更新记录.
>更新记录时,如果check_status字段为1,则保留描述和注释字段.
>更新记录时,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(描述)会在DB表中给出现有记录(即“现有描述”)的值.但是,它似乎给了我试图插入的内容,即“一些描述”.
有没有人知道如何使用SQL正确地做到这一点.尝试upsert时,引用现有记录中的值的最佳方法是什么?