How to Fix MySQL Error Code 1215: Cannot Add Foreign Key Constraint

If you are experiencing MySQL Error Code 1215, it means that you are unable to add a foreign key constraint to your table. This error usually occurs due to a mismatch in the data types of the columns or the key columns not being indexed.

├Źndice
  1. Steps to Fix MySQL Error Code 1215

Steps to Fix MySQL Error Code 1215

Here are the steps you can follow to fix MySQL Error Code 1215:

  1. Check the data types of the columns: Make sure that the data types of the columns in both the referencing and referenced tables are the same. If there is a mismatch, you need to make the necessary changes to ensure that the data types match.
  2. Check if the key columns are indexed: The columns that are used as foreign keys must be indexed. If they are not indexed, you need to create the necessary indexes.
  3. Check the order of the CREATE TABLE statements: If you are creating the tables in a different order than the order in which they are referenced, you will get this error. Make sure that you create the referenced table first, followed by the referencing table.
  4. Check for duplicate keys: If there are duplicate keys in the referencing table, you need to remove them before adding the foreign key constraint.

By following these steps, you should be able to fix MySQL Error Code 1215 and add the necessary foreign key constraint to your table.


CREATE TABLE referenced_table (
  id INT PRIMARY KEY
);

CREATE TABLE referencing_table (
  id INT,
  referenced_id INT,
  FOREIGN KEY (referenced_id) REFERENCES referenced_table(id)
);

Make sure to use the correct data types and index the necessary columns to avoid this error in the future.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information