Domanda

I'd like to perform a little bit complicated upsert operation using INSERT ... ON DUPLICATE KEY UPDATE. But I couldn't get it to work.

This is what I'd like to do:

  1. Try inserting a record. If the insert succeeds, that's good.
  2. If that record exists, update the record.
  3. When updating the record, if check_status field is 1, then leave description and comment field.
  4. When updating the record, it check_status field is 0, then update description and comment field as well.

Before writing out the SQL, let's assume that there is the following record in some_table:

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

So in order to do the operation I described above, I used SQL as follows:

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')

I thought VALUES(description) would give me the value of the existing record (i.e. 'existing description') in the DB table. However, it seems to give me what I tried to insert i.e. 'some description'.

Does anybody know how to do this correctly using SQL. What's the best way to refer to the value in the existing record when trying to upsert?

È stato utile?

Soluzione

Simple. Don't use VALUES() (you're already doing it to refer to the existing value of 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')

Or use it to set the new content rather than repeating yourself:

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))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top