2016-12-24 110 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 | 
相關問題