Home > Net >  How to create a mysql query that checks if a row exists - if it does I want to insert a new record o
How to create a mysql query that checks if a row exists - if it does I want to insert a new record o

Time:07-06

I have a table which has an ID and an occurrences column. I want to create a single transaction to the db where

if ID exists in DB:
    occurrences  
else:
    insert new row where occurrences = 1

I saw that it's possible to do an IF THEN statement so I was attempting to do something like this:

IF ID = 123 IS NOT NULL THEN
    UPDATE occurrences = occurrences  1
ELSE
    INSERT INTO entity_table(123, 1)
END IF;

CodePudding user response:

INSERT INTO entity_table SET id=123, occurrences = 1
ON DUPLICATE KEY UPDATE occurrences = occurrences   1
  • Related