create table test (
id int8 generated always as identity,
username text not null unique,
touch_count int4 not null default 0,
primary key (id)
);
merge into test t
using (values ('super')) as i(un)
on t.username = i.un
when matched then
update set touch_count = touch_count + 1
when not matched then
insert (username, touch_count) values (i.un, 1);
MERGE 1
select * from test;
id | username | touch_count
----+----------+-------------
1 | super | 1
(1 row)
merge into test t
using (values ('super')) as i(un)
on t.username = i.un
when matched then
update set touch_count = touch_count + 1
when not matched then
insert (username, touch_count) values (i.un, 1);
MERGE 1
select * from test;
id | username | touch_count
----+----------+-------------
1 | super | 2
(1 row)
merge into test t
using (values ('super')) as i(un)
on t.username = i.un
when matched and touch_count < 3 then
update set touch_count = touch_count + 1
when matched then
delete
when not matched then
insert (username, touch_count) values (i.un, 1);
MERGE 1
select * from test;
id | username | touch_count
----+----------+-------------
1 | super | 3
(1 row)
merge into test t
using (values ('super')) as i(un)
on t.username = i.un
when matched and touch_count < 3 then
update set touch_count = touch_count + 1
when matched then
delete
when not matched then
insert (username, touch_count) values (i.un, 1);
MERGE 1
select * from test;
id | username | touch_count
----+----------+-------------
(0 rows)
原文作者:SQL编程思想;如有侵权,请联系管理员删除。