Skip to content Skip to sidebar Skip to footer

How To Check Existing Record Before Inserting Record For Each User Into Same Table?

I have table where I wanted to store one more key for each user, following is the table, I was trying to add app_reminder for each existing users. I did it by following insert

Solution 1:

One method simply uses conditional aggregation:

insertinto users_settings (user_id, key)
    select user_id, 'app_reminder'from users_settings
    groupby user_id
    havingsum(key ='app_reminder') =0;

You might want a more generic solution. If you want to ensure that user/key pairs are never duplicated, then create a unique constraint or index on those columns:

altertable users_settings addconstraint unq_users_settings_user_id_key
    unique (user_id, key);

Then, you can skip inserting the rows using on duplicate key update:

insertinto users_settings (user_id, key)
    selectdistinct user_id, 'app_reminder'from users_settings
    on duplicate key update user_id =values(user_id);

The update does nothing, because the value is the same. MySQL skips doing the insert and does not return an error.

Post a Comment for "How To Check Existing Record Before Inserting Record For Each User Into Same Table?"