2

I know that I can use "ON DUPLICATE KEY UPDATE" when I want to update a row if exists, or insert otherwise. But in my case, I want to update based on non-unique keys.

E.g: I have a table with 3 columns: A, B and C. All of them together form the unique key.
Now I want to update the row if the value of B and C match, or else insert a new row.

Can this be done in MySQL without multiple queries.

5
  • 1
    Presumably you mean "columns", instead of "rows"? If you always update (instead of insert) when the columns match, surely you end up effecting a uniqueness constraint anyway - so why not include it in your schema? Or are there occasions when you will insert irrespective of existing "duplicate" records?
    – eggyal
    Jan 11, 2013 at 17:54
  • no the uniqueness is never broken Jan 11, 2013 at 18:01
  • 1
    Well if A,B,C together would form a unique key - how would you select the row you want to update when B and C match you can have more than one updated. That's why ON DUPLICATE KEY UPDATE won't work. If you say you just update all matching rows, you will cause a duplicate key error Jan 11, 2013 at 18:01
  • well the logic is such that in certain cases B and C match only one row, and I wanna update only that row Jan 11, 2013 at 18:03
  • I say you can't do that in one query if you don't wrap that into a function or procedure Jan 11, 2013 at 18:04

1 Answer 1

0

If there were unique keys, you could use REPLACE INTO. If you don't have these unique values, you need to use two queries. Query 1 is a select for update, query two is either an update (if the count of rows returned is > 0) or an insert (if no rows were returned)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.