skip to Main Content

I have table firebaseTokens with columns userId and tokenValue. When a user logs in, my ReactJS frontend grabs the device token and assigns it to the logged in user via the userId column. A user may have many tokens, and a token may have many users – so neither userId column not tokenValue can be a primary key. I want my INSERT query to check for a duplicate row, i.e. userId=11 and tokenValue=123456. If a userId/tokenValue row matching the INSERT query already exists, then no new row is created. But if no such row already exists, then INSERT the row. What is the proper syntax for this?

2

Answers


  1. In addition on what @stu mention, look at this: MySQL INSERT IGNORE

    INSERT IGNORE INTO firebaseTokens (userId, tokenValue)
    VALUES (11, '123456');
    
    Login or Signup to reply.
  2. You can use REPLACE INTO to Insert if not exist and update if exists, only if you have (userId, tokenValue) as a composite unique index as mentioned by Stu:

    REPLACE INTO firebaseTokens (userId, tokenValue)
    VALUES (11, '123456');
    

    Demo here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search