Skip to content

外键 Constraint Violation

错误信息

                violates 外键 constraint
              

快速摘要

你 tried 到 insert or 更新行 使用外键值 那个做 不 match 任何主键 in referenced 表.

为什么发生

  • Inserting child 记录之前 parent 记录 exists

  • 删除 parent 记录那个 still 有 child 记录 referencing 它

  • 设置外键到 值那个做 不 exist in parent 表

  • Typo in 外键值

最小示例

✗ 错误代码
INSERT INTO orders (id, user_id, total) VALUES (1, 999, 50.00);
-- But user 999 does not exist
✓ 修复代码
-- Create the user first
INSERT INTO users (id, name) VALUES (999, 'Ada');
INSERT INTO orders (id, user_id, total) VALUES (1, 999, 50.00);

顺序 referenced 非-existent 用户. 创建用户首先 satisfies 外键 constraint.

如何诊断

  • 读取错误到 identify 哪个外键 constraint 是 violated

  • 检查如果 referenced parent 记录 exists: SELECT * FROM parent_table WHERE id = 值

  • 检查如果 child 记录 exist 之前删除 parent

如何修复

  • 创建 parent 记录首先, 然后 child 记录

  • 删除 or reassign child 记录之前删除 parent

  • Use ON DELETE CASCADE 如果 child 记录应该是 移除 automatically

  • 正确外键值 到引用 existing 记录

如何预防

  • 总是创建 parent 记录之前 child 记录

  • Use cascading 删除 or 更新哪里 appropriate

  • 验证外键引用 in 你的 application 之前 inserting

相关资源

相关术语

相关课程

  • 关系

    学习关于 foreign 键 and referential integrity.

← 返回语言