Can't create table xxx (errno: 150) error solution
In general, the cause of this problem is that the created foreign key does not match the primary key type of the associated table . Let's use a simple example to illustrate.
Two very simple tables, the student table and the teacher table:
-
CREATE
TABLE
`t_teacher` (
-
`id`
varchar(
11)
NOT
NULL,
-
`name`
varchar(
20)
DEFAULT
NULL,
-
PRIMARY
KEY (
`id`)
-
)
ENGINE=
InnoDB
DEFAULT
CHARSET=utf8;
-
-
CREATE
TABLE
`t_student` (
-
`id`
varchar(
11)
NOT
NULL
DEFAULT
'',
-
`name`
varchar(
20)
DEFAULT
NULL,
-
PRIMARY
KEY (
`id`)
-
)
ENGINE=
InnoDB
DEFAULT
CHARSET=utf8;
Now you need to create a foreign key to the student table to associate the teacher table:
The first case, very simple, is that the column types do not match
For example, use int type columns to associate varchar columns:
-
ALTER
TABLE
`t_student`
-
ADD
COLUMN
`teacher_id`
int(
11)
NULL
AFTER
`name`;
-
-
ALTER
TABLE
`t_student`
ADD
CONSTRAINT
`teacher_id_fk`
FOREIGN
KEY (
`teacher_id`)
REFERENCES
`t_teacher` (
`id`)
ON
DELETE RESTRICT
ON
UPDATE RESTRICT;
In another case, although the data type is the same, the character encoding is inconsistent
E.g:
The last case is that the column referenced by the foreign key cannot be found.
When adding a foreign key, column data may already exist (historical data, or the default value set when updating the database table), but these data may not necessarily find the corresponding row record in the foreign key association table. This situation will also cause the foreign key creation to fail.
Continuously updating...
Article reference learning address: https://blog.csdn.net/imhuqiao/article/details/51432051