Solution to the problem of cannot add foreign key constraint

Solution to the problem of cannot add foreign key constraint

01 Occurrence scene

  • When I add a foreign key to a mysql database table

Insert image description here

02 Causes of exceptions and their solutions

  • There are several key points to pay attention to when adding foreign keys, otherwise it is easy to fail.

1. Data types must be consistent

Insert image description here

  • The data type of the item added to the foreign key and the reference item must be the same. The error I reported here is because one is int and the other is bigint.

2. The foreign key name is unique

Insert image description here

  • Foreign key names cannot be repeated

3. The default settings of foreign keys must be consistent

Insert image description here

  • The reference table here is checked and unsigned by default, but I forgot to check it before, and now I have corrected it.

  • Whether the previous picture is null is also a key point. Focusing on checking the key points can effectively avoid errors.

03 Problem Solving

  • After I changed the data type to bigint (my default setting) and checked unsigned, the foreign key was added successfully, which is gratifying.

Guess you like

Origin blog.csdn.net/2302_77182979/article/details/134980471
Recommended