MySQL - insert if doesn't exist yet

Richard Rodriguez picture Richard Rodriguez · Jan 26, 2013 · Viewed 15.8k times · Source

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?

Answer

John Woo picture John Woo · Jan 26, 2013

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`)