Mysql solution to failure to add foreign keys: 1. Check whether the types or sizes of the two fields match and modify them; 2. Create an index for the field where the foreign key is set; 3. Check the engine type of the table, And modify it to InnoDB engine; 4. Check whether the foreign key name is unique and modify it; 5. Modify the attribute value of cascade or set the field attribute to allow null, etc.
The operating environment of this tutorial: Windows 10 system, MySQL version 5.7, Dell G3 computer.
What should I do if mysql fails to add a foreign key?
MySQL foreign key creation failure reasons
First of all, if data has been inserted into several tables related to the foreign key, it may cause the foreign key insertion to fail
When creating foreign keys in MySQL, we often encounter problems and fail. This is because there are many details in MySQL that we need to pay attention to. I have summarized and reviewed the information and listed the following common reasons. .
1. The types or sizes of the two fields do not strictly match. For example, if one is int(10), then the foreign key must also be set to int(10), not int(11), and not tinyint. In addition, you must also determine whether one of the two fields is signed and the other is unsigned (ie: unsigned). The two fields must match strictly. For more information about signed and unsigned, please see: http: //www.verysimple.com/blog/?p=57
2. The field trying to set a foreign key is not indexed, or is not a primary key. If one of them is not the primary key, you must first create an index for it.
3. One or two of the tables are MyISAM engine tables. If you want to use foreign key constraints, the table must be of the InnoDB engine (actually, if both tables are of the MyISAM engine, this error will not occur at all, but the foreign key will not be generated, only the index will be created) You need to check The engine type of the table.
4. The name of the foreign key cannot be repeated. You should check your database to make sure the foreign key names are unique, or you can add a few random characters after the key name to test if this is the cause.
5. You may have set ON DELETE SET NULL, but the related key fields are set to NOTS NULL values. You may solve the problem by modifying the cascade attribute value or setting the field attribute to allow null.
6. Please make sure your Charset and Collate options are consistent at the table level and field level.
7. You may have set a default value for the foreign key, such as default=0.
8. There are syntax errors in the ALTER statement
When an error occurs, carefully check the design of the database tables and fields. I also recommend that everyone try to use tools to design and create databases, which can reduce the probability of errors.
Recommended learning: "MySQL Video Tutorial"
The above is the detailed content of What to do if mysql fails to add foreign key. For more information, please follow other related articles on the PHP Chinese website!

MySQLstringtypesimpactstorageandperformanceasfollows:1)CHARisfixed-length,alwaysusingthesamestoragespace,whichcanbefasterbutlessspace-efficient.2)VARCHARisvariable-length,morespace-efficientbutpotentiallyslower.3)TEXTisforlargetext,storedoutsiderows,

MySQLstringtypesincludeVARCHAR,TEXT,CHAR,ENUM,andSET.1)VARCHARisversatileforvariable-lengthstringsuptoaspecifiedlimit.2)TEXTisidealforlargetextstoragewithoutadefinedlength.3)CHARisfixed-length,suitableforconsistentdatalikecodes.4)ENUMenforcesdatainte

MySQLoffersvariousstringdatatypes:1)CHARforfixed-lengthstrings,2)VARCHARforvariable-lengthtext,3)BINARYandVARBINARYforbinarydata,4)BLOBandTEXTforlargedata,and5)ENUMandSETforcontrolledinput.Eachtypehasspecificusesandperformancecharacteristics,sochoose

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
