


Why Am I Getting 'Error Code: 1005' When Adding a Foreign Key to My MySQL Table?
Dec 10, 2024 am 04:06 AMTroubleshooting Foreign Key Addition to Table
When attempting to add a foreign key to an existing table named "katalog", an error message may be encountered: "Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)."
Causes:
- Syntax error in the ALTER TABLE statement: The provided syntax includes an incorrect reference to the table mytable.#sql-7fb1_7d3a instead of katalog.
- Missing or invalid reference to the referenced table: Ensure that the referenced table (Sprache in this case) exists and has an appropriately matching column (ID in this case).
- Incompatibility between table and reference column attributes: Verify that the data types and constraints of the foreign key column and the referenced column are compatible.
Resolution:
- Correct the syntax in the ALTER TABLE statement to reference the correct table name, katalog.
- Ensure that the referenced table, Sprache, exists with an ID column that matches the foreign key constraint.
- Verify that the data types and constraints of the foreign key column (Sprache in this case) match those of the referenced column (ID in Sprache) in the referenced table.
Example:
To successfully add the foreign key, use the following corrected ALTER TABLE statement:
ALTER TABLE katalog ADD CONSTRAINT `fk_katalog_sprache` FOREIGN KEY (`Sprache`) REFERENCES `Sprache` (`ID`) ON DELETE SET NULL ON UPDATE SET NULL;
The above is the detailed content of Why Am I Getting 'Error Code: 1005' When Adding a Foreign Key to My MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Reduce the use of MySQL memory in Docker

How do you alter a table in MySQL using the ALTER TABLE statement?

How to solve the problem of mysql cannot open shared library

What is SQLite? Comprehensive overview

Run MySQl in Linux (with/without podman container with phpmyadmin)

Running multiple MySQL versions on MacOS: A step-by-step guide

How do I secure MySQL against common vulnerabilities (SQL injection, brute-force attacks)?

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?
