关系 "publications" 的列 "new" 不存在

column "new" of relation "publications" does not exist

我想开发一个在插入或更新后更新触发器的触发器。

我遵循此 tutorial 并创建了一个在插入后由触发器调用的函数。我之前和之后都试过了。

DROP TRIGGER IF EXISTS answer_update_question_timestamp ON public.publications;

CREATE OR REPLACE FUNCTION trigger_update_question_timestamp()
  RETURNS TRIGGER AS $func$
BEGIN
    UPDATE publications SET new.last_edit_date = now() WHERE publicationid = new.publicationid;
    RETURN NULL;
END;
$func$  LANGUAGE plpgsql;

CREATE TRIGGER answer_update_question_timestamp AFTER INSERT OR UPDATE ON publications
   FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();




CREATE TABLE publications
(
    publicationid SERIAL PRIMARY KEY,
    body VARCHAR(1000) NOT NULL ,
    creation_date TIMESTAMP DEFAULT now() NOT NULL,
    userid INTEGER NOT NULL,
    last_edit_date TIMESTAMP,
    CONSTRAINT body_length CHECK (CHAR_LENGTH(body) >= 10 AND CHAR_LENGTH(body) <= 1000),
    CONSTRAINT "FK_publications_users"
        FOREIGN KEY ("userid") REFERENCES users ("userid") ON DELETE SET NULL ON UPDATE CASCADE
);

我注意到 NEW 不适用于 FOR EACH STATEMENT 等操作,但我没有发现 FOR EACH ROW

有任何问题

有人知道我做错了什么吗?

亲切的问候

如果您希望 last_edit_date 在插入或删除时设置为 now(),只需将默认设置为 now():

CREATE TABLE publications
(
 ...
    last_edit_date TIMESTAMP DEFAULT now(),
....
);

如果你仍然想去那里,而不是更新自身并返回 null 为 NEW 分配一个新值:

NEW.last_edit_date := now(); 
RETURN NEW;

pozs 所说的无限循环发生在您 将更新 table 的函数分配给 table 上的触发器时,该触发器在更新时触发

更新 - OP 的工作示例:

t=# CREATE TABLE publications
(
    publicationid SERIAL PRIMARY KEY,
    body VARCHAR(1000) NOT NULL ,
    creation_date TIMESTAMP DEFAULT now() NOT NULL,
    userid INTEGER NOT NULL,
    last_edit_date TIMESTAMP
);
CREATE TABLE
t=# CREATE OR REPLACE FUNCTION trigger_update_question_timestamp()
  RETURNS TRIGGER AS $func$
BEGIN
    new.last_edit_date := now();
    RETURN NEW;
END;
$func$  LANGUAGE plpgsql;
CREATE FUNCTION
t=# CREATE TRIGGER answer_update_question_timestamp BEFORE INSERT OR UPDATE ON publications
   FOR EACH ROW EXECUTE PROCEDURE trigger_update_question_timestamp();
CREATE TRIGGER
t=# insert into publications select 1,'2',now(),3,null;
INSERT 0 1
t=# select * from publications;
 publicationid | body |       creation_date        | userid |       last_edit_date
---------------+------+----------------------------+--------+----------------------------
             1 | 2    | 2017-03-30 15:28:10.897846 |      3 | 2017-03-30 15:28:10.897846
(1 row)