当COALESCE()应该确保不为null时,为什么违反了NOT NULL约束?

时间:2018-08-23 20:47:06

标签: postgresql

我有一个约有20行的PostgreSQL表。我正在尝试从另一个架构中的相似表将数据导入其中。源表具有空值字段。目标表不允许其中一些为空。我正在使用COALESCE将任何空值替换为默认值。但是,当我尝试导入行时,出现了NOT NULL约束冲突。

如果除去表中除主键和不可为空的列之外的所有列,则查询有效!

这是插入查询:

insert into alarm_history_minimum
(alarm_history_pkey, area)
select alarm_pkey,coalesce(area, 'All'::character varying)
from old_public.alarm_history
where alarm_pkey = 82234;

这是最小化的表:

CREATE TABLE public.alarm_history_minimum
(
    alarm_history_pkey bigint NOT NULL,
    area character varying(32) COLLATE pg_catalog."default" NOT NULL DEFAULT 'All'::character varying
)

这是完整表:

CREATE TABLE public.alarm_history
(
    alarm_history_pkey bigint NOT NULL,
    area character varying(32) COLLATE pg_catalog."default" NOT NULL DEFAULT 'All'::character varying,
    device character varying(32) COLLATE pg_catalog."default",
    alarm_number smallint NOT NULL DEFAULT 0,
    tag character varying(32) COLLATE pg_catalog."default",
    state smallint NOT NULL,
    message text COLLATE pg_catalog."default",
    alarm_date timestamp with time zone,
    charge integer,
    ack_date timestamp with time zone,
    ack_state integer NOT NULL DEFAULT 0,
    furnace character varying(32) COLLATE pg_catalog."default",
    cooling_cover character varying(32) COLLATE pg_catalog."default",
    heating integer,
    base character varying(32) COLLATE pg_catalog."default",
    CONSTRAINT alarm_history_pk PRIMARY KEY (alarm_history_pkey),
    CONSTRAINT alarm_history_base_fk FOREIGN KEY (area, base)
        REFERENCES public.bases (area, base) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        DEFERRABLE INITIALLY DEFERRED,
    CONSTRAINT alarm_history_charge_fk FOREIGN KEY (charge)
        REFERENCES public.charges (charge) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        DEFERRABLE INITIALLY DEFERRED,
    CONSTRAINT alarm_history_cooler_fk FOREIGN KEY (cooling_cover, area)
        REFERENCES public.cooling_covers (cover, area) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        DEFERRABLE INITIALLY DEFERRED,
    CONSTRAINT alarm_history_device_fk FOREIGN KEY (device)
        REFERENCES public.bases (alarm_device) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        DEFERRABLE INITIALLY DEFERRED,
    CONSTRAINT alarm_history_furnace_fk FOREIGN KEY (furnace, area)
        REFERENCES public.furnaces (furnace, area) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        DEFERRABLE INITIALLY DEFERRED
)

1 个答案:

答案 0 :(得分:0)

我忘记了我的alarm_history表具有触发器。空值来自由该触发器更新的表。在进行转换工作之前,那个触发因素已经使我痛苦不堪,我忘了。

我感谢那些发表问题和评论的人,并为自己的愚蠢行为而使名单混乱不已表示歉意。再次。