PostgresSQL:更新表B中的某些列后,更新表B中的某些列

时间:2018-11-09 11:58:01

标签: postgresql sql-function postgresql-triggers

我在Postgres中有2个表,假设CategoryThread具有一对多关系

Category

id   | title | created_at | deleted_at 
-----+-------+------------+-----------

Thread

id   | category_id | title | created_at | deleted_at 
-----+-------------+-------+------------+-----------

我想创建一个触发器:如果我在Category中执行软删除(将deleted_at从null更新为now()),则Threaddeleted_at应该会得到也已更新。

这是我的职能

    CREATE OR REPLACE FUNCTION "thread_soft_delete"()
    RETURNS trigger
    AS $pg1$
    BEGIN
    UPDATE thread SET deleted_at = NOW()
    FROM "category"
    WHERE thread.category_id = "category".id;
    RETURN NULL;
    END;
    $pg1$
    VOLATILE
    LANGUAGE plpgsql;

这里是触发器

    CREATE TRIGGER category_delete
    AFTER UPDATE ON "category"
    FOR EACH ROW
    WHEN (OLD.deleted_at IS DISTINCT FROM NEW.deleted_at)
    EXECUTE PROCEDURE thread_soft_delete();

当我运行update "category" set deleted_at = now() WHERE id = 1;时,created_at中的所有thread列都会更新。我期望只有category_id = 1的行要更新。

请帮助我

1 个答案:

答案 0 :(得分:0)

您无需在触发函数中引用category表。只需NEW.id()就可以了。

CREATE OR REPLACE FUNCTION "thread_soft_delete"()
RETURNS trigger
AS $pg1$
BEGIN
UPDATE thread SET deleted_at = NOW()
WHERE thread.category_id = NEW.id;
RETURN NULL;
END;
$pg1$
VOLATILE
LANGUAGE plpgsql;