在SQL中将INTERVAL添加到TIME

时间:2018-07-30 23:23:01

标签: sql postgresql sqldatatypes

在PostgreSQL中(使用pgAdmin 3 ...这是我的学校要求我们使用的)当我尝试检查触发器是否NEW事件与另一个事件同时发生时,我收到一条错误消息上。 “ stime”的数据类型为TIME,代表“开始时间”,“ duration”的数据类型为INTERVAL。

if (NEW.stime >= schedule.stime AND NEW.stime <= (schedule.stime + schedule.duration))
--Checking if the new event happens while another event is.

给定的错误如下:

    ERROR:  missing FROM-clause entry for table "schedule"
LINE 5:   (NEW.stime >= schedule.stime AND NEW.stime <= (schedule.st...
                        ^
QUERY:  SELECT (NEW.sdate IN (SELECT sdate FROM schedule)) AND
        --Checking for events in the room at given date.
        (NEW.rno IN (SELECT rno FROM schedule WHERE NEW.sdate = schedule.sdate AND NEW.bno = schedule.bno)) AND
        --Checking if the new event happens while another event is.
        (NEW.stime >= schedule.stime AND NEW.stime <= (schedule.stime + schedule.duration))
CONTEXT:  PL/pgSQL function trigf1() line 12 at IF
********** Error **********

ERROR: missing FROM-clause entry for table "schedule"
SQL state: 42P01
Context: PL/pgSQL function trigf1() line 12 at IF

我还要在此处发布所需的房间和时间表创建信息以及触发器:

CREATE TABLE room (

rno INT     NOT NULL,

bno INT     NOT NULL,

function VARCHAR (30),

capacity INT,

PRIMARY KEY (rno, bno)

);

CREATE TABLE schedule (

sdate DATE  NOT NULL,

stime TIME  NOT NULL,

rno INT     NOT NULL,

bno INT     NOT NULL,

eid INT     NOT NULL,

duration INTERVAL,

FOREIGN KEY (rno, bno) REFERENCES room (rno, bno)

CREATE OR REPLACE FUNCTION trigf1() RETURNS TRIGGER AS $$

DECLARE

BEGIN
    IF 
    --Checking if the new event is in revent or sevent
    (NEW.eid IN (SELECT reid FROM revent) OR (NEW.eid IN (SELECT seid FROM sevent))) AND
    --Checking if the room exsists
    (NEW.rno IN (SELECT rno FROM room)) AND 
    (NEW.bno IN (SELECT bno FROM room WHERE NEW.rno = room.rno) ) THEN
        IF
        --Checking for other events on the same day.
        (NEW.sdate IN (SELECT sdate FROM schedule)) AND
        --Checking for events in the room at given date.
        (NEW.rno IN (SELECT rno FROM schedule WHERE NEW.sdate = schedule.sdate AND NEW.bno = schedule.bno)) AND
        --Checking if the new event happens while another event is.
        (NEW.stime >= schedule.stime AND NEW.stime <= (schedule.stime + schedule.duration)) THEN
        BEGIN
            RAISE NOTICE 'ERROR: Could not add given row to schedule';
            RETURN NULL;
        END;
        END IF;
    END IF;
    RETURN NEW;

END;
$$ LANGUAGE plpgsql;


CREATE TRIGGER T1 BEFORE INSERT ON schedule

FOR EACH ROW

EXECUTE PROCEDURE trigf1();

1 个答案:

答案 0 :(得分:0)

未经查询,您将无法访问schedule中的行。尝试改变

(NEW.stime >= schedule.stime AND NEW.stime <= (schedule.stime + schedule.duration))

收件人:

EXISTS (SELECT *
               FROM schedule
               WHERE new.stime >= schedule.stime
                     AND new.stime <= (schedule.stime + schedule.duration))

但是您的构造似乎会检查每个所需条件,并且只有在一切正常的情况下,它才会引发错误。也许您需要否定一切。