【问题标题】:How to insert trigger in PostgreSQL?如何在 PostgreSQL 中插入触发器?
【发布时间】:2019-12-14 10:15:49
【问题描述】:

我有两张桌子:

  1. users
  2. trainer

users 表中,我默认有一列is_trainer=false

当用户在users表中输入信息并选择is_trainer=true列时,我想在trainer表中插入用户信息。

当我省略if条件时,在users表中插入用户后,它会将信息放入trainer表中,但是当我输入if条件时,它不起作用!我认为它认为is_trainer 用于trainer 表而不是users

我的代码:

BEGIN
    IF NEW.is_trainer <> OLD.is_trainer THEN
        INSERT INTO trainer(trainer_id, sport_id, fee_per_hour, experience, created_by)
        VALUES(users.user_id, 3, '200$', 3, 6);
    END IF;
    RETURN NEW;
END;

【问题讨论】:

    标签: sql postgresql sql-insert database-trigger


    【解决方案1】:

    这不会像你期望的那样工作:

    IF NEW.is_trainer <> OLD.is_trainer THEN
    

    INSERT 触发器中,没有OLD 值,即伪表OLD 中的所有列都是NULL。所以你的表达可以归结为:

    IF NEW.is_trainter <> NULL THEN
    

    这个条件永远不会成立,因为与NULL 没有什么不同,也不等于NULL(要检查是否为空,您需要IS NULL)。

    根据您对需求的描述,我认为您想要:

    IF NEW.is_traiter = true THEN
    

    另外,您的INSERT 命令将不起作用,因为它引用了未知关系users。你可能想要:

    INSERT INTO trainer(trainer_id,sport_id,fee_per_hour,experience,created_by)
    VALUES(NEW.user_id, 3, '200$', 3, 6);
    

    您为插入trainer 提供的其他值也可能来自伪表NEW(例如created_by)。

    【讨论】:

    • 只是一个小笔记。如果正如暗示的那样,列 is_trainer 被定义为布尔值,则构造“If new.is_trainer = true then”可以简化为“If new.is_trainer then”。
    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    相关资源
    最近更新 更多