我正试图插入一个表(mdata),其中有一个堆肥外键引用到另一个表(测量)中的主键,不幸的是,我有这个错误
ERROR: insert or update on table "mdata" violates foreign key constraint "FK_mdata"
DETAIL: Key (time, measurement_id)=(2022-07-18 12:35:03.31052, 1) is not present in table "measurement".
SQL state: 23503
注意外键数据存在于引用表中。下面是我的两个表格
CREATE TABLE IF NOT EXISTS public.mdata
(
id bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
value jsonb NOT NULL,
measurement_id bigint NOT NULL,
"time" timestamp without time zone NOT NULL,
CONSTRAINT "PK_medata" PRIMARY KEY (id),
CONSTRAINT "FK_mdata" FOREIGN KEY ("time", measurement_id)
REFERENCES public.measurement ("time", id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE CASCADE
)
和
CREATE TABLE IF NOT EXISTS public.measurement
(
id bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 9223372036854775807 CACHE 1 ),
"time" timestamp without time zone NOT NULL,
value real NOT NULL,
CONSTRAINT "PK_measurement" PRIMARY KEY ("time", id),
)
问题是我没有看到这个问题,因为我确信我插入到mdata (measurement_id和"time")中的内容肯定存在于测量表中。有谁能给点提示吗?
我正在尝试像这样插入
INSERT INTO public.mdata(
id, value, measurement_id, "time")
VALUES (8, '{}',1 , '2022-07-18 12:35:03.31052');
经过调查,唯一可能的原因是,表测量可能是一个继承表,感谢@Craig Ringer这个答案(PostgreSQL中的外键+表继承?),这促使我仔细检查是否有任何继承到我的表:https://www.postgresql.org/docs/current/ddl-inherit.html DDL-INHERIT-CAVEATS
因此,继承确实导致了INSERT违例。