Can't create table xxx (errno: 150) error when MySQL creates foreign keys

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:


 
  
  
  1. CREATE TABLE `t_teacher` (
  2. `id` varchar( 11) NOT NULL,
  3. `name` varchar( 20) DEFAULT NULL,
  4. PRIMARY KEY ( `id`)
  5. ) ENGINE= InnoDB DEFAULT CHARSET=utf8;
  6. CREATE TABLE `t_student` (
  7. `id` varchar( 11) NOT NULL DEFAULT '',
  8. `name` varchar( 20) DEFAULT NULL,
  9. PRIMARY KEY ( `id`)
  10. ) 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:


 
  
  
  1. ALTER TABLE `t_student`
  2. ADD COLUMN `teacher_id` int( 11) NULL AFTER `name`;
  3. 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

Guess you like

Origin blog.csdn.net/weixin_44325444/article/details/107757275