I have a requirement to update a record if it exists else insert it. I know this has been asked a few times but I think my problem is a bit trickier.
I have a table (tbl_settings):
setting_id | token | setting_value | setting_for
1 1 on background
2 1 off vibrate
3 2 on vibrate
etc
This is for a mobile app which I will save the users settings in a remote DB so the can retrieve later if needed.
Setting_id is unique and auto increment.
Token is going to be the devices token id (user specific)
Setting_value is the value (on/off) for that particular setting
Setting_for is the name of the actual setting
Now there are 4 setting options available to a user which can be written to the DB at individual times (when the user changes the setting on/off) or together if its better.
So if the user changes the vibrate setting, I need a query to check if vibrate and token exist update that particular record otherwise insert with token, setting_value and setting_for.
Hopefully its possible in a single query. If not I will just use multiple queries, one to check if it exists and the other to insert or update.
MySQL offers two options for this:
replace intoinsert ... on duplicate updateDo note that in both cases you’ll have to drop your
setting_id(which seems pointless anyway) and use a composite primary key.