2016-12-24 54 views
0

是否可以插入记录以检查现有记录是否早于N天。如果是,则创建一个新记录,否则只更新现有的记录。只有当现有记录早于N天时才能插入

+0

有了大概的触发器。 –

+0

如果可能,我想避免这种用法,并坚持查询 – Tarlen

+2

请[编辑]你的问题,并为有问题的表(包括主键和索引定义)添加'create table'语句,一些样本数据和基于样本数据的预期结果。 [_Formatted_](http://dba.stackexchange.com/help/formatting)**文本**请[无屏幕截图](http://meta.stackoverflow.com/questions/285551/why-may-i -not-upload-images-code-on-so-when-asking-question-285557#285557) –

回答

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 | 
相关问题