更新Postgres表中的日期范围

时间:2016-04-14 19:52:21

标签: sql postgresql date

我有日期表:

select id,date date_ranges where range_id = 1;
1 2016-04-12
2 2016-04-13
3 2016-04-14

我也有一个数组:

示例:

array('2016-04-11','2016-04-12','2016-04-13','2016-04-14','2016-04-15')

array('2016-04-13','2016-04-14','2016-04-15')

如何在不更改现有表值的情况下将数组中的新值插入到表中? 如果我有第二个数组,我怎么能从表中删除值2016-04-12?

帮助PLZ,我需要一个查询)

1 个答案:

答案 0 :(得分:1)

WITH current_values AS (
    SELECT generate_series('2016-04-13'::DATE, '2016-04-17'::DATE, '1 day')::DATE AS date
), 
deleted_values AS (
    DELETE FROM date_ranges WHERE date NOT IN (SELECT * FROM current_values) RETURNING id
)
INSERT INTO date_ranges ("date", range_id) 
    WITH new_values AS (
        SELECT new."date" 
        FROM current_values AS new 
        LEFT JOIN date_ranges AS old 
            ON old."date" = new."date" 
        WHERE old.id IS NULL
    ) 
    SELECT date, 1 FROM new_values;