Home >Database >Mysql Tutorial >Why is My Foreign Key Constraint Incorrectly Formed?

Why is My Foreign Key Constraint Incorrectly Formed?

DDD
DDDOriginal
2025-01-19 05:45:10358browse

Why is My Foreign Key Constraint Incorrectly Formed?

Database foreign key constraint error: data type and length mismatch

In foreign key relationships between tables, the "Foreign key constraint is malformed" error may be caused by inconsistent data types and lengths of the columns involved.

To resolve this error, please make sure the following conditions are met:

  1. Data type matching: The data type of the foreign key column (IDFromTable1) in Table 2 must be the same as the data type of the referenced column (ID) in Table 1. In this example, both columns are specified as CHAR type. If they are different types (for example, INT vs. VARCHAR), the foreign key constraint has no effect.
  2. Equal length: If both columns are character (CHAR/VARCHAR) data types, they must also have the same length (number of characters). In the given example, if IDFromTable1 is defined as CHAR(5) and ID is defined as CHAR(10), creating the foreign key constraint will fail with a "Malformed" error.

By resolving these issues and ensuring that the foreign key and reference columns have matching data types and lengths, the foreign key relationship can be established correctly, allowing for the expected cascading delete operation.

The above is the detailed content of Why is My Foreign Key Constraint Incorrectly Formed?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn