I'm trying to make a site where people can sign up for events + an activity assigned to that event. They can choose which one they want to attend, or even both.
For that I made a table named "eventCounter"
Image of table
userID, eventID and activityID are all FK poiting to other tables.
They should be able to update their current "status", so they can join the activity after they signed up for the event.
So my question is: How can I make a If else saying if row exists update else insert
IF EXISTS(select userID, eventID, activityID from eventCounter where userID=1 and eventID=1)
THEN
UPDATE eventcounter SET activityID=1 WHERE userID=1;
ELSE
INSERT INTO eventcounter (userID, activityID) VALUES(1,1)
I don't think the ON DUPLICATE key will work as I have 2 columns that needs to be checked?
We can perform MySQL UPSERT operation mainly in three ways, which are as follows: UPSERT using INSERT IGNORE. UPSERT using REPLACE. UPSERT using INSERT ON DUPLICATE KEY UPDATE.
With the INSERT IGNORE statement, MySQL will insert a new row only if the values don't exist in the table.
That's what is called an Upsert
. The MySQL syntax is pretty weird, but you can do it, something like:
INSERT INTO eventcounter (userID, eventID, activityID) VALUES(1,1,1)
ON DUPLICATE KEY UPDATE
activityID = VALUES(activityID)
It only works for duplicate PKs though (not for any field you like), so in this case it would only work if userID
and eventID
compose the PK and you only want to change the activityID
Otherwise, you could go the IF-ELSE route, something like:
DECLARE mycount INT;
SET mycount = (SELECT COUNT(*) FROM eventcounter WHERE userID=1 AND eventID=1);
IF mycount > 0 THEN
UPDATE eventcounter SET activityID=1 WHERE userID=1 AND eventID=1;
ELSE
INSERT INTO eventcounter (userID, eventID, activityID) VALUES(1,1,1);
END IF;
Disclaimer: totally untested code
@Jcl
's answer:One thing you have to bear in mind is that this statement only works if a duplication occurs either to PRIMARY KEY
or UNIQUE INDEX
in case of inserting (so not only PK
but index
also works)!
SQL command:
INSERT INTO fooTable (RowNum, name, lastname, userID, score) VALUES(3,'Michael','Widenius','1012141618',19.75)
ON DUPLICATE KEY UPDATE name = 'Allan', lastname = 'Larsson', userNum = '2022242628', score = 10.50;
Note:
VALUES()
to refer to the new row and columns is deprecated (Reference)MYSQL 8.0
and PHP Mysqli
too.name
, lastname
and userID
in case that record is already exist and score
would be enough!I found it pretty straight and easy to perform, you can check duplication on almost every important field in your case (using UNIQUE INDEX
s)! just remember the very first line...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With