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)

Sign up to request clarification or add additional context in comments.

9 Comments

@Dave: what actually?
two fields = 1 primary key
@Dave: I didn't mention primary key in my answer
oh sorry im so used to primary key being unique that i thought they were the same things.
Well i created a unique key with the two fields. And kept id as PK
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.