Clint
Clint

Reputation: 93

MySQL Update if row exists, otherwise insert

INSERT INTO GameScoreTotal (
    `GameName`
    , `OverallScore`
    , `GraphicsScore`
    , `StoryScore`
    , `GameplayScore`
    , `TimeScore`
    )
VALUES (
    'HomeFront'
    , '1'
    , '1'
    , '1'
    , '1'
    , '5'
    )
WHERE GameName = 'HomeFront'
    ON DUPLICATE KEY

UPDATE OverallScoreTotal = OverallScoreTotal + '1'
    , GraphicsTotal = GraphicsTotal + '1'
    , StoryTotal = StoryTotal + '1'
    , GameplayTotal = GameplayTotal + '1'
    , TimeTotal = TimeTotal + '1'
    , RatingCount = RatingCount + 1;

I am trying to update GameScoreTotal If we have something there otherwise insert. Any ideas?

Upvotes: 3

Views: 2671

Answers (2)

John Woo
John Woo

Reputation: 263723

  • you need to define key on GameName name, (a unique or primary key should do)
  • remove WHERE clause from the insert statement

query,

INSERT INTO GameScoreTotal ( `GameName` , `OverallScore` , `GraphicsScore`
                           , `StoryScore` , `GameplayScore`  , `TimeScore` )
VALUES ( 'HomeFront' , 1  , 1 , 1 , 1 , 5 )
    ON DUPLICATE KEY
UPDATE OverallScoreTotal = OverallScoreTotal + 1
     , GraphicsTotal = GraphicsTotal + 1
     , StoryTotal = StoryTotal + 1
     , GameplayTotal = GameplayTotal + 1
     , TimeTotal = TimeTotal + 1
     , RatingCount = RatingCount + 1;

SOURCE

Upvotes: 7

John3136
John3136

Reputation: 29265

Lookup REPLACE INTO instead of INSERT INTO.

Upvotes: 0

Related Questions