1

I have this table:

rating | businessId | userId
============================
  1          200        1
  2.5        200        2

the user can't has two rows with the same businessId, for example:

    rating | businessId | userId
    ============================
      1          200        1
      2.5        200        1

this's incorrect;

my server receive the businessId,userId and rating.

then it should update the row which has the same userId, and businessId if exist, else create new row.

How could I implement that with one query ?

david
  • 17
  • 5

2 Answers2

1

It is possible to perform a single query which will either insert or update a row, by using MySQL procedures. However, it's very likely to be better to test whether the row exists first in your chosen language, and then either insert or update as appropriate. This will allow you to give appropriate feedback to the user, and other things which depend on whether the row existed before.

gandaliter
  • 9,863
  • 1
  • 16
  • 23
0

Suppose you get these three values @rating ,@userId,@businessId then you would write you UPSERT (UPDATE/Insert) query something like this.....

IF EXISTS (SELECT 1 FROM dbo.TableName 
            WHERE userId = @userId AND businessId = @businessId)
 BEGIN
        UPDATE dbo.TableName 
         SET businessId = @businessId
            ,rating     = @rating
        WHERE  userId = @userId
 END
ELSE 
 BEGIN
    INSERT INTO dbo.TableName (userId, businessId, rating)
    VALUES (@userId, @businessId, @rating)
 END
M.Ali
  • 67,945
  • 13
  • 101
  • 127