问题描述:

  在创建外键约束时mysql 报 Create table 'tempdb/student' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns.

这个问题是主表和从表在列上的数据类型不一致造成的

 

mysql> create table teacher
    -> (id int auto_increment primary key,
    -> name varchar(16) char set utf8
    -> );
Query OK, 0 rows affected (0.05 sec)

mysql> 
mysql> 
mysql> create table student
    -> (id int auto_increment primary key,
    -> name varchar(16) char set utf8,
    -> teacher_id varchar(16) char set utf8, -- 注意问题在这里 teahcer_id 的类型错了
    -> constraint foreign key fk_teacher_id (teacher_id) references teacher(id)
    -> );
ERROR 1215 (HY000): Cannot add foreign key constraint
Warning (Code 150): Create table 'tempdb/student' with foreign key constraint failed. There is no index in the referenced table where the referenced columns appear as the first columns.

Error (Code 1215): Cannot add foreign key constraint

 

改正:

只要数据类型调整过来就行了

mysql> create table teacher
    -> (id int auto_increment primary key,
    -> name varchar(16) char set utf8
    -> );
s teacher(id)
);Query OK, 0 rows affected (0.04 sec)

mysql> 
mysql> create table student
    -> (id int auto_increment primary key,
    -> name varchar(16) char set utf8,
    -> teacher_id int,
    -> constraint foreign key fk_teacher_id (teacher_id) references teacher(id)
    -> );
Query OK, 0 rows affected (0.01 sec)

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-24
  • 2022-01-15
  • 2021-12-04
  • 2021-10-04
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-08-24
  • 2021-12-03
  • 2022-12-23
  • 2021-07-13
  • 2021-08-09
  • 2021-05-27
相关资源
相似解决方案