PostgreSQL Insert into with case 和 concat

PostgreSQL Insert into with case and concat

我正在尝试制作一个插入触发器,它将从 table A 中获取两个字符串字段(x 和 y)并将它们连接到 table B 中的单个字段中。如果 y 是不为空,我想在连接时在 x 和 y 之间添加一个“-”。到目前为止,我的代码如下所示:

BEGIN
    INSERT INTO B(xy,z)
        SELECT y,z,
            CASE WHEN y IS NOT NULL then concat('some prefix',x,' - ',y)
                ELSE concat('some prefix',x)
            END
        FROM(SELECT NEW.x, NEW.y NEW.z) as n;
        WHERE [some conditions]
    RETURN NEW;
END;

据我了解,它应该将 'some prefix x - y' 或 'some prefix x' 放置在 table B 的 xy 字段中,并将来自 A 的 z 放置在 B 的 z 中,但我得到了错误 "INSERT has more expressions than target columns"。有人知道我做错了什么吗?

你的外部 select 列表有三个术语 - yzcase 表达式,只需删除 y 并重新排序其他两个和你应该没问题:

INSERT INTO B(xy,z)
SELECT
    CASE WHEN y IS NOT NULL then concat('some prefix',x,' - ',y)
        ELSE concat('some prefix',x)
    END, -- First expression, goes into b.xy
    z -- SEcond expression, goes into b.z
FROM(SELECT NEW.x, NEW.y NEW.z) as n;
WHERE [some conditions]