更新不允许其他记录中的日期范围的查询

时间:2017-01-07 04:41:05

标签: postgresql

在Postgres中,记录包含startdate,enddate和其他字段。更新记录时,不应允许记录已有的日期。我需要一个查询来更新不允许重复记录的记录

1 个答案:

答案 0 :(得分:0)

CREATE TABLE t 
(
    pid INTEGER,
    aid INTEGER,
    startdate DATE,
    enddate DATE
) ;


WITH data_to_insert (pid, aid, startdate, enddate) AS
(
    VALUES (1, 1, date '2017-01-01', date '2017-01-31')
)
INSERT INTO 
    t (pid, aid, startdate, enddate)
SELECT
    *
FROM
    data_to_insert
WHERE 
    NOT EXISTS 
    (
    SELECT * 
    FROM t 
        JOIN data_to_insert 
            ON (t.startdate, t.enddate) 
            OVERLAPS (data_to_insert.startdate, data_to_insert.enddate)
    ) ;

或者,使用您的变量(应该sanitized来避免SQL注入):

INSERT INTO 
    t (pid, aid, startdate, enddate)
VALUES
    ($prjid, $allocid, date $stdate, date $enddate)
WHERE 
    NOT EXISTS 
    (
    SELECT * 
    FROM t 
        JOIN data_to_insert 
            ON (t.startdate, t.enddate) 
            OVERLAPS (date $stdate, date $enddate)
    ) ;