Home >Database >Mysql Tutorial >How to Troubleshoot MySQL Error 1022: Duplicate Key in Table Creation?
Duplicate Key Error in Table Creation: Troubleshooting "Error 1022"
A user encountered the infamous "Error 1022: Can't write; duplicate key in table" error while attempting to create a new table. Upon examining the SQL query, the source of the duplication was not immediately evident.
The query created a table named usercircle with multiple columns, including idUserCircle, userId, and circleId. It also specified a primary key on idUserCircle and foreign key constraints referencing the user and circle tables on the userId and circleId columns, respectively.
Identifying the Conflict
The key to resolving this error lies in recognizing that constraints, including foreign key constraints, must be unique across the entire database, not just within a specific table. Therefore, the underlying issue is likely a duplicate constraint name elsewhere in the database.
Solution
To determine which constraints are conflicting, the user can execute the following query:
SELECT `TABLE_SCHEMA`, `TABLE_NAME` FROM `information_schema`.`KEY_COLUMN_USAGE` WHERE `CONSTRAINT_NAME` IN ('iduser', 'idcategory');
This query will reveal which tables and columns are currently using the iduser and idcategory constraints. By renaming the duplicate constraint(s), the user can resolve the error and successfully create the usercircle table.
Additional Tips
The above is the detailed content of How to Troubleshoot MySQL Error 1022: Duplicate Key in Table Creation?. For more information, please follow other related articles on the PHP Chinese website!