Skip to content

唯一 Constraint Violation

错误信息

                duplicate 键值 violates 唯一 constraint
              

快速摘要

你 attempted 到 insert or 更新行 使用值 那个 already exists in 列 marked UNIQUE or PRIMARY KEY.

为什么发生

  • Inserting duplicate email, 用户名, or other 唯一值

  • Manually 设置主键值 那个 already exists

  • race 条件哪里 two 请求 try 到 insert 相同值 simultaneously

  • 不检查 for existing 记录之前 inserting

最小示例

✗ 错误代码
INSERT INTO users (id, email) VALUES (1, '[email protected]');
-- But a row with id=1 already exists
✓ 修复代码
INSERT INTO users (id, email) VALUES (1, '[email protected]')
ON CONFLICT (id) DO NOTHING;

ON CONFLICT DO NOTHING skips insert 如果行 使用 id=1 already exists, avoiding 错误.

如何诊断

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

  • 查询 for existing 记录: SELECT * FROM 表 WHERE 列 = 值

  • 检查如果你的 application 有 duplicate-prevention 检查

如何修复

  • Use 不同值 那个做 不 already exist

  • Use INSERT ... ON CONFLICT DO NOTHING (PostgreSQL) or INSERT IGNORE (MySQL) 到 skip duplicates

  • Use INSERT ... ON CONFLICT DO UPDATE 到 upsert 相反的 erroring

  • 检查 for existing 记录之前 inserting

如何预防

  • 总是检查 for existing 记录之前 inserting 唯一值

  • Use upsert 模式 (ON CONFLICT / ON DUPLICATE KEY UPDATE)

  • Handle 唯一 violation 错误 gracefully in 你的 application

相关资源

相关术语

相关课程

← 返回语言