0

I have a query which updates the table or inserts if the row does not already exist, but for some reason it just inserts all the time.

This is my table structure:

Id (primary) | uid | product_id | quantity

This is my query:

INSERT INTO my_table (uid,product_id,quantity) 
    SELECT t1.uid,?,?
    FROM checker t1
    WHERE t1.id = ?
ON DUPLICATE KEY UPDATE
    product_id = ?, quantity = quantity+?

What i want to do though is use on duplicate key if uid + product_id combination exist in the table already.

So is there a way to designate what kind of duplication to look for to update instead of insert?

1 Answer 1

1

There is no way to distinguish between what duplication occurs.

As soon as any unique constraint is violated - it will perform ON DUPLICATE KEY UPDATE part.

For your case you just need to create unique composite key that consists of 2 fields: (uid, product_id)

9
  • @Dave: what actually?
    – zerkms
    Jul 17, 2013 at 4:56
  • two fields = 1 primary key
    – Sir
    Jul 17, 2013 at 4:56
  • @Dave: I didn't mention primary key in my answer
    – zerkms
    Jul 17, 2013 at 4:56
  • oh sorry im so used to primary key being unique that i thought they were the same things.
    – Sir
    Jul 17, 2013 at 4:57
  • 1
    Well i created a unique key with the two fields. And kept id as PK
    – Sir
    Jul 17, 2013 at 5:10

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.