MySQL - insert if doesn't exist yet
16,697
Solution 1
you can use ON DUPLICATE KEY UPDATE
INSERT INTO `cron-stats` (`user`) VALUES ('yourValue')
ON DUPLICATE KEY UPDATE user = user;
but in order to perform the INSERT
statement well, you need to set a UNIQUE
index on column user
.
if the column has no index
yet, execute the statement below,
ALTER TABLE `cron-stats` ADD CONSTRAINT tb_un UNIQUE (`user`)
Solution 2
A little bit hacky, but if you use a SELECT
derived table instead of VALUES
you can do:
INSERT INTO `cron-stats`(`user`)
SELECT u
FROM (SELECT @dByUser AS u) x
WHERE NOT EXISTS(SELECT 1 FROM `cron-stats` WHERE `user` = @dByUser)
Author by
Frantisek
An aspiring writer hoping to one day write a video game.
Updated on July 22, 2022Comments
-
Frantisek almost 2 years
I want to execute this MySQL query:
INSERT INTO `cron-stats` (`user`) VALUES (".(int)$d['by-user'].")
Whenever such user doesn't exist yet, as in:
SELECT 1 FROM `cron-stats` WHERE `user` = ".(int)$d['by-user']."
How can I execute this in one query?
-
Frantisek over 11 yearsNot sure if this helps. I'm using this in a CRON, where I'm running
UPDATE
for existing entries. Before theUPDATE
runs, I want to prepare not existing entries by INSERTing null values. Is this the proper solution? -
John Woo over 11 yearswhat's the reason why you need to insert null values first?
-
Frantisek over 11 yearsOh well, it doesn't work. Here's the full query with the error: pastebin.com/PyHMY9RG
-
John Woo over 11 yearsyou have key word
SET
in the query which is not suppose to be there. remove it and execute it again. -
John Woo over 11 yearsit's not the same. Oh, i see a
WHERE
clause at the end of the query. remove it also. -
John Woo over 11 years
-
Brett over 9 yearsThis is a terrible solution since you're losing out hugely on performance benefits and ACID. You'd really need to wrap this in a transaction to make it work right, and why would you do that anyway when there are clear commands that are so much better?
-
Rich S about 6 yearsInterestingly, when you use the 'duplicate_key_update' statement and it prevents an insert, it still advances the AUTO_INCREMENT for that table.
-
Cruncher over 5 yearsIs this guaranteed to be atomic? That is, if two inserts come in at the same time, could they both pass the WHERE NOT EXISTS part and both insert?