1

First of, I've searched this topic here and elsewhere online, and found numorous articles and answers, but none of which did this...

I have a table with ratings, and you should be able to update your rating, but not create a new row.

My table contains: productId, rating, userId

If a row with productId and userId exists, then update rating. Else create new row.

How do I do this?

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
curly_brackets
  • 5,491
  • 15
  • 58
  • 102

3 Answers3

4

First add a UNIQUE constraint:

ALTER TABLE tableX
  ADD CONSTRAINT productId_userId_UQ
    UNIQUE (productId, userId) ;

Then you can use the INSERT ... ON DUPLICATE KEY UPDATE construction:

INSERT INTO tableX
  (productId, userId, rating)
VALUES
  (101, 42, 5),
  (102, 42, 6),
  (103, 42, 0)
ON DUPLICATE KEY UPDATE
  rating = VALUES(rating) ;

See the SQL-Fiddle

ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
0

You are missing something or need to provide more information. Your program has to perform a SQL query (a SELECT statement) to find out if the table contains a row with a given productId and userId, then perform a UPDATE statement to update the rating, otherwise perform a INSERT to insert the new row. These are separate steps unless you group them into a stored procedure.

Piovezan
  • 3,215
  • 1
  • 28
  • 45
0

Use a REPLACE INTO query.

REPLACE INTO table (productId, userId, rating) VALUES ('product id', 'user id', 'rating');

REPLACE INTO is like a normal insert, except if it finds a row already in the table with the same unique key it will delete that row before inserting.

Bad Wolf
  • 8,206
  • 4
  • 34
  • 44
  • Your unique key should be a composite key of product_id and user_id, in this case it also happens to be your primary key. When the query runs, if it finds an existing product_id and user_id combination it will delete that row then perform the insert. – Bad Wolf Jun 06 '13 at 19:09
  • `REPLACE` has several disdvantages. Read this: [“INSERT IGNORE” vs “INSERT … ON DUPLICATE KEY UPDATE”](http://stackoverflow.com/questions/548541/insert-ignore-vs-insert-on-duplicate-key-update) – ypercubeᵀᴹ Jun 06 '13 at 19:13