# PDOException：SQLSTATE[23000]：完整性约束违反：键 'users_email_unique' 的重复条目 'john@example.com'

- **ID:** `php/pdo-sqlstate-23000-duplicate-entry-unique-constraint`
- **领域:** php
- **类别:** data_error
- **错误码:** `1062`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

INSERT 或 UPDATE 操作尝试在具有 UNIQUE 约束的列中创建重复值，通常由于竞态条件、缺少检查或并发请求导致。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| MySQL 8.0.34 | active | — | — |
| MariaDB 10.11.0 | active | — | — |
| PHP 8.2.0 | active | — | — |

## 解决方案

1. ```
   使用 INSERT IGNORE 或 ON DUPLICATE KEY UPDATE 优雅处理重复：
$stmt = $pdo->prepare('INSERT INTO users (email, name) VALUES (:email, :name) ON DUPLICATE KEY UPDATE name = VALUES(name)');
$stmt->execute([':email' => 'john@example.com', ':name' => 'John']);
   ```
2. ```
   实现带有短暂延迟的重试机制：
try { $stmt->execute(); } catch (PDOException $e) { if ($e->errorInfo[1] == 1062) { usleep(100000); $stmt->execute(); } else { throw $e; } }
   ```

## 无效尝试

- **Removing the UNIQUE constraint on the column to allow duplicates** — This violates data integrity and can lead to application logic bugs; not a real fix but a workaround that breaks the schema. (95% 失败率)
- **Wrapping every INSERT in a SELECT to check existence first without using transactions** — Race conditions still occur between SELECT and INSERT in concurrent environments; does not solve the problem reliably. (80% 失败率)
