Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - insert if doesn't exist yet

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?

like image 610
Frantisek Avatar asked Jan 26 '13 07:01

Frantisek


2 Answers

you can use ON DUPLICATE KEY UPDATE

INSERT INTO `cron-stats` (`user`) VALUES ('yourValue')
ON DUPLICATE KEY UPDATE user = user;
  • ON DUPLICATE KEY UPDATE

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`)
like image 50
John Woo Avatar answered Oct 31 '22 18:10

John Woo


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)

SQL Fiddle demo

like image 32
lc. Avatar answered Oct 31 '22 19:10

lc.