存在外键时违反外键约束

rah*_*hul 1 sql database postgresql foreign-key-relationship

我是PostgreSQL和数据库的新手,并且试图弄清楚为什么即使存在外键时也会收到外键冲突。

我跑的查询

insert into analytics_url_redirect
(source, news_item_id, access_date)
select 'n',id,CURRENT_TIMESTAMP from entry_entry_master
where id=43068778;
Run Code Online (Sandbox Code Playgroud)

这失败了

ERROR: insert or update on table "analytics_url_redirect" violates foreign key constraint "news_item_id_refs_id_15ddd78c"
SQL state: 23503
Detail: Key (news_item_id)=(43068778) is not present in table "entry_entry_master".
Run Code Online (Sandbox Code Playgroud)

以下选择查询也可以正常工作并返回43068778:

select id  from entry_entry_master where id=43068778;
Run Code Online (Sandbox Code Playgroud)

整个create table命令-django sqlall的输出是

BEGIN;
CREATE TABLE "analytics_url_redirect" (
    "id" serial NOT NULL PRIMARY KEY,
    "newsletter_id" integer REFERENCES "nlc_newsletter" ("newslettercore_ptr_id") DEFERRABLE INITIALLY DEFERRED,
    "alert_id" integer REFERENCES "alerts_emailtracker" ("id") DEFERRABLE INITIALLY DEFERRED,
    "source" varchar(1) NOT NULL,
    "brief_id" integer REFERENCES "brief_brief" ("id") DEFERRABLE INITIALLY DEFERRED,
    "news_item_id" integer REFERENCES "entry_entry_master" ("id") DEFERRABLE INITIALLY DEFERRED,
    "external_news_item_id" integer REFERENCES "nlc_newsletterblock" ("id") DEFERRABLE INITIALLY DEFERRED,
    "recipient_id" integer REFERENCES "subscriber_subscriber" ("id") DEFERRABLE INITIALLY DEFERRED,
    "external_recipient_id" integer REFERENCES "subscriber_pseudosubscriber" ("id") DEFERRABLE INITIALLY DEFERRED,
    "access_date" timestamp with time zone NOT NULL
)
;
CREATE INDEX "analytics_url_redirect_newsletter_id" ON "analytics_url_redirect" ("newsletter_id");
CREATE INDEX "analytics_url_redirect_alert_id" ON "analytics_url_redirect" ("alert_id");
CREATE INDEX "analytics_url_redirect_brief_id" ON "analytics_url_redirect" ("brief_id");
CREATE INDEX "analytics_url_redirect_news_item_id" ON "analytics_url_redirect" ("news_item_id");
CREATE INDEX "analytics_url_redirect_external_news_item_id" ON "analytics_url_redirect" ("external_news_item_id");
CREATE INDEX "analytics_url_redirect_recipient_id" ON "analytics_url_redirect" ("recipient_id");
CREATE INDEX "analytics_url_redirect_external_recipient_id" ON "analytics_url_redirect" ("external_recipient_id");
CREATE INDEX "analytics_url_redirect_access_date" ON "analytics_url_redirect" ("access_date");
COMMIT;
Run Code Online (Sandbox Code Playgroud)

那么,当存在外键时,如何可能违反外键约束?我是否缺少明显的东西?

rah*_*hul 5

我自己弄清楚了。:(

我错过的一个细节是entry_entry_master是使用表继承进行分区的。从postgres文档中:postgres继承

继承功能的一个严重限制是索引(包括唯一约束)和外键约束仅适用于单个表,不适用于它们的继承子级。在外键约束的引用端和被引用端均是如此。

这也解释了为什么选择查询有效。