Mysql主表与字表关于外键的情况

针对Innodb引擎
给学生表添加数据时,如果添加的teacher_id在它的主表中不存在则会存在问题,因此,通过外键进行设置, 使得保证添加的teacher_id都在teacher表的id里,下面有两种方法,第一是给已经创建好的表格追加, 第二是在创建的时候设置的。 1.已经创建的表格,通过修改语句添加外键: 语法:alter table 子表表名 add constraint foreign key 外键名称 (当前表的字段) references 主表表名 (主表的主键); alter table student add constraint foreign key fk_class_id (class_id) references class (id); 2.创建表的时候指定外键: create table student1 ( id int(11) primary key auto_increment, name varchar(10) not null unique, class_id int(11), ... constraint foreign key fk_class_id (class_id) references class(id) ); 注意:建立外键,主表和子表相关联的两个字段的数据类型以及附加选项都必须一样。
知识来源于彭老师。

猜你喜欢

转载自www.cnblogs.com/zpdbkshangshanluoshuo/p/10059193.html
今日推荐