Solution to the problem of cannot add foreign key constraint
01 Occurrence scene
- When I add a foreign key to a mysql database table
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
- 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
- Foreign key names cannot be repeated
3. The default settings of foreign keys must be consistent
-
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.