【问题标题】:PostgreSQL Foreign Key Constraint cannot Find Existing KeyPostgreSQL 外键约束找不到现有键
【发布时间】:2014-07-17 01:00:10
【问题描述】:

我有这张桌子:

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。

这可能是什么原因造成的,我该如何补救?

【问题讨论】:

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


【解决方案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(机器检查异常)、查找存储错误消息、检查磁盘等。

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

【讨论】:

    猜你喜欢
    • 2019-04-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2018-04-04
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多