PostgreSQL外键约束无法找到现有密钥

时间:2014-07-17 01:00:10

标签: sql postgresql postgresql-9.1 postgresql-9.2 postgresql-9.3

我有这张桌子:

CREATE TABLE operation_history
(
  id bigserial NOT NULL,
  task_history bigint NOT NULL,
  operation smallint NOT NULL,
  CONSTRAINT operation_history_pkey PRIMARY KEY (id),
  CONSTRAINT operation_history_operation_fkey FOREIGN KEY (operation)
             REFERENCES desktop_operation (id) MATCH SIMPLE
             ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT operation_history_task_history FOREIGN KEY (task_history)
             REFERENCES task_history (id) MATCH SIMPLE
             ON UPDATE NO ACTION ON DELETE NO ACTION
)

我有另一个表task_history,其中有三行,其中id为:1,2,3。但是,出于某种原因,当我在operation_history表上插入时,我收到一条错误,指出task_history行与我给它的id不存在。以下是要插入的查询:

INSERT INTO operation_history (task_history, operation) VALUES
(1, 2);

这是错误:

ERROR:  insert or update on table "operation_history" violates foreign key constraint "operation_history_task_history"
DETAIL:  Key (task_history)=(1) is not present in table "task_history".

我肯定知道,task_history表中有三行包含id 1,2和3。

可能导致此问题的原因以及如何解决?

1 个答案:

答案 0 :(得分:1)

尝试:

SET enable_seqscan = off;
SELECT t.id FROM task_history t WHERE t.id = 1;    

SET enable_seqscan = on;
SET enable_indexscan = off;
SET enable_indexonlyscan = off;
SELECT t.id FROM task_history t WHERE t.id = 1;

如果结果不同,那么您的索引可能已损坏。这不应该发生。如果您不在当前的PostgreSQL补丁版本上,请立即升级并REINDEX。如果您是,我会检查机器上的内存问题,最近的MCE(机器检查异常),查找存储错误消息,检查磁盘等等。

如果查询产生相同的结果,那么您的表格内容或定义并不是您认为的。