Mysql跟Oracle中更新表记录,若不存在,则直接插入记录的操作

Mysql和Oracle中更新表记录,若不存在,则直接插入记录的操作

有类似这样的场景,比如对某种数据进行统计,每增加一条,就对表A中对应统计记录的值+1,若统计表中,没有对应这种情况的统计数据,则需新插入一条记录,后续在遇到这种数据时,对数据进行更新。

这个时候可以直接用数据库sql实现。

mysql: on Duplicate key update
oracel: merge
//创建一个表
create table  daily_hit_counter(
day date mot null,
slot number not null,
cnt number not null,
private key(day,slot)
)
 
mysql:
INSERT INTO daily_hit_counter(DAY,slot,cnt) VALUES (CURRENT_DATE,RAND()*100,1)
     ON DUPLICATE KEY UPDATE cnt=cnt+1;
 
oracel:
//此sql并未执行验证,格式大概如此
merge into daily_hit_counter t1
using (select trunc(sysdate,'dd') day,dbms_random.value slot,1 cnt from dual) t2
on(t1.day=t2.day and t1.slot=t2.slot) 
when not matched then insert values (t2.day,t2.slot,1)
when matched then update set t1.cnt= t1.cnt+1;