当前位置: 首页 >数据库 > mysql 创建外键引用时眼瞎了,然而mysql 报的错也是认人摸不着头脑

mysql 创建外键引用时眼瞎了,然而mysql 报的错也是认人摸不着头脑

问题描述:

  在创建外键约束时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 constraintWaing (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)

 

来源链接:https://www.cnblogs.com/JiangLe/p/5807099.html

版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。





本文链接:https://www.javaclub.cn/database/118341.html

标签:Cannot add
分享给朋友:

“mysql 创建外键引用时眼瞎了,然而mysql 报的错也是认人摸不着头脑” 的相关文章

MySQL表的增删改查(进阶) 2022年05月16日 21:54:11
sql递归查询 2022年05月17日 21:40:33
mysql之基础查询 2022年06月06日 00:56:31
mysql的查询句 2022年06月09日 23:40:52
MySql 查询两张表的数据差别 2022年06月11日 20:14:35
mysql 查询某字段最小的记录 2022年06月12日 13:41:31
MySQL查询指定行的记录 2022年06月14日 06:02:58
MySQL查询优化 2022年06月14日 16:56:49