MySQL - insert if doesn't exist yet

2019-04-23 14:28发布

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?

3条回答
Melony?
2楼-- · 2019-04-23 14:41

You can try this using if else condition

$chk = mysql_query("select 'the username' FROM `cron-stats`");
$rs = mysql_fetch_array($chk);
if($rs == "")
{
    $ins = mysql_query("INSERT INTO `cron-stats` (`user`) VALUES ('.(int)$d['by-user'].')");
} 
else{
    echo "Duplicate entry";
}
查看更多
劳资没心,怎么记你
3楼-- · 2019-04-23 14:42

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`)
查看更多
仙女界的扛把子
4楼-- · 2019-04-23 14:55

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

查看更多
登录 后发表回答