MySQL追加额外检查

MySQL追加额外检查,mysql,database,upsert,Mysql,Database,Upsert,我想使用INSERT执行一个稍微复杂的upsert操作。。。在重复密钥更新时。但我无法让它工作 这就是我想做的: 尝试插入一条记录。如果插入成功,那就好了 如果该记录存在,请更新该记录 更新记录时,如果check_status字段为1,则保留description和comment字段 更新记录时,检查_status字段是否为0,然后更新description和comment字段 在写出SQL之前,假设在某个表中有以下记录: column name | val -------------

我想使用
INSERT执行一个稍微复杂的upsert操作。。。在重复密钥更新时
。但我无法让它工作

这就是我想做的:

  • 尝试插入一条记录。如果插入成功,那就好了
  • 如果该记录存在,请更新该记录
  • 更新记录时,如果check_status字段为1,则保留description和comment字段
  • 更新记录时,检查_status字段是否为0,然后更新description和comment字段
  • 在写出SQL之前,假设在某个表中有以下记录:

    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')
    
    我认为值(描述)会给出DB表中现有记录(即“现有描述”)的值。然而,它似乎给了我我试图插入的东西,即“一些描述”


    有人知道如何使用SQL正确地执行此操作吗。在尝试向上插入时,引用现有记录中的值的最佳方式是什么?

    简单。不要使用
    VALUES()
    (您这样做是为了引用
    check\u 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, VALUES(description))
    comment = IF(check_status = 1, comment, VALUES(comment))
    

    哈哈。哎哟,就这么简单!谢谢你的回答@eggyal!
    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))