This question here:
MySQL: INSERT IGNORE or ON DUPLICATE KEY UPDATE with checking multiple and not unique columns
Is similar, but not quite.
I am trying to build a watch list, using a table as follows:
recordId | itemId | userId | dateAdded
The recordId is the only unique column and ss an autoincrement ID field.
itemId, userId and dateAdded can be duplicated individually, but not altogether.
So, if a user has already added an item to his/her watch list, I want it to just update the dateAdded.
Rows therefore may contain the same userId many times (as the user may wish to ‘watch’ multiple items) and it may include the itemId many times (as the same item may be ‘watched’ by many users) but a combination of both the userId and itemId matching a record which already exists should cause an update.
Is there a single statement way to do this, or do I need to ask the database if userId = & postingUser & and itemId = & requestedId & before attempting an insert?
Here’s how you can do this:
where the ?’s stand for the new values you’re inserting
This is assuming you have defined a unique index for
(itemId, userId):How this works:
(itemId, userId), this will be checkedon duplicate keyclause, which updates thedateAddedcolumn’s value