php - Fastest way to update a MySQL table if row exists else insert. More than 2 non-unique keys -
i have next table structure:
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`) )
currently check & insert/update next snippet:
$checkq = mysql_query("select count(*) rowexist reports day='$day' , uid='$uid' , siteid='$sid' , cid='$cid'") or die(mysql_error()); $checkr = mysql_fetch_array($checkq); if ($checkr['rowexist'] > 0) { mysql_query("update reports_adv set visits=visits+1 day='$day' , uid='$uid' , siteid='$sid' , cid='$cid'"); } else { mysql_query("insert reports_adv set day='$day', uid='$uid', siteid='$sid', cid='$cid', visits='1'"); }
is fastest way update mysql table if row exists else insert more 2 non-unique keys?
just utilize insert...on duplicate key update
insert reports_adv (day, uid, siteid, cid, visits) values ('$day', '$uid', '$sid', '$cid', 1) on duplicate key update visits=visits+1;
insert ... on duplicate key update syntax but before else, should define unique
constraint on columns.
alter table reports_adv add together constraint tb_uq unique (day, uid, siteid, cid)
php mysql sql sql-update sql-insert
No comments:
Post a Comment