小编典典

如果存在行或插入,则更新MySQL表的最快方法。超过2个非唯一键

sql

我具有以下表结构:

 CREATE TABLE IF NOT EXISTS `reports` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `day` int(11) NOT NULL,
  `uid` int(11) NOT NULL,
  `siteid` int(11) NOT NULL,
  `cid` int(3) NOT NULL,
  `visits` int(11) NOT NULL,
  PRIMARY KEY (`id`)
 )

目前,我使用以下代码段检查和插入/更新:

 $checkq = mysql_query("SELECT count(*) as rowexist FROM reports WHERE day='$day' AND uid='$uid' AND siteid='$sid' AND cid='$cid'") or die(mysql_error()); 
$checkr = mysql_fetch_array($checkq);

if ($checkr['rowexist'] > 0) {
 mysql_query("UPDATE reports_adv SET visits=visits+1 WHERE  day='$day' AND uid='$uid' AND siteid='$sid' AND cid='$cid'"); 
} else {
 mysql_query("INSERT INTO reports_adv SET day='$day', uid='$uid', siteid='$sid', cid='$cid', visits='1'");
}

如果存在行,否则插入超过2个非唯一键是更新此MySQL表的最快方法吗?


阅读 172

收藏
2021-03-23

共1个答案

小编典典

只是使用 INSERT...ON DUPLICATE KEY UPDATE

INSERT INTO reports_adv (day, uid, siteid, cid, visits) 
VALUES ('$day', '$uid', '$sid', '$cid', 1)
ON DUPLICATE KEY UPDATE visits=visits+1;

但在进行其他操作之前,您应该UNIQUE在列上定义约束。

ALTER TABLE reports_adv  ADD CONSTRAINT tb_uq UNIQUE (day, uid, siteid, cid)
2021-03-23