仅在现有记录超过N天时才进行Upsert

时间:2016-12-24 08:37:32

标签: sql postgresql

是否可以以检查现有记录是否早于N天的方式来记录记录。如果是,则创建新记录,否则只更新现有记录

1 个答案:

答案 0 :(得分:1)

如果您更喜欢纯SQL解决方案,请尝试以下方式。

样本数据:

create table abcd(
  id serial,
  name varchar(100),
  value int,
  created date
 );

 insert into abcd( name, value, created) values
 ( 'name 1', 10, current_date - interval '10' day),
 (  'name 2', 55, current_date - interval '120' day);

 ;

 select * from abcd;

id |name   |value |created    |
---|-------|------|-----------|
1  |name 1 |10    |2016-12-14 |
2  |name 2 |55    |2016-08-26 |

查询:

 with  records  as (
    select *,
           case when created >= current_date - interval '10' day
                then 'UPDATE' else 'INSERT' end as what_to_do
    from abcd
 ),
 up_date as (
    update abcd set value = 1000
    where id in (select id from records where what_to_do = 'UPDATE')
    returning id
 ),
 in_sert as (
    insert into abcd( name, value, created)
    select name, 1000, current_date
    from records where what_to_do = 'INSERT'
    returning id
 )
 select *  from up_date 
 union all
 select *  from in_sert
 ;

select * from abcd; 
id |name   |value |created    |
---|-------|------|-----------|
2  |name 2 |55    |2016-08-26 |
1  |name 1 |1000  |2016-12-14 |
3  |name 2 |1000  |2016-12-24 |