The most likely you already have a constraint with the name iduser
or idcategory
in your database. Just rename the constraints if so.
Constraints must be unique for the entire database, not just for the specific table you are creating/altering.
To find out where the constraints are currently in use you can use the following query:
SELECT `TABLE_SCHEMA`, `TABLE_NAME`
FROM `information_schema`.`KEY_COLUMN_USAGE`
WHERE `CONSTRAINT_NAME` IN ('iduser', 'idcategory');
Change the Foreign key name in MySQL. You can not have the same foreign key names in the database tables.
Check all your tables and all your foreign keys and avoid having two foreign keys with the same exact name.
From the two linksResolved Successfully and Naming Convention, I easily solved this same problem which I faced. i.e., for the foreign key name, give as fk_colName_TableName. This naming convention is non-ambiguous and also makes every ForeignKey in your DB Model unique and you will never get this error.
Error 1022: Can't write; duplicate key in table
As others have mentioned, it's possible that the name for your constraint is already in use by another table in your DB. They must be unique across the database.
A good convention for naming foreign key constraints is:
fk_TableName_ColumnName
To investigate whether there's a possible clash, you can list all constraints used by your database with this query:
SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB';
When I ran this query, I discovered I had previously made a temporary copy of a table and this copy was already using the constraint name I was attempting to use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With