外键约束 foreign key

外键约束 :保持数据一致性,完整性实现一对多关系。
外键必须关联到键上面去,一般情况是,关联到另一张表的主键

(因为一个表只存一类信息。用外键来做参照,保证数据的一致性,可以减少数据冗余)

##表a
create table a(
    a_id int primary key auto_increment,
    a_name varchar(20) not null
);
insert into a values(1,'a1'),(2,'a2');

##表b
create table b(
    b_id int primary key,
    b_name varchar(20) not null,
    fy_id int not null,
    constraint AB_id foreign key(fy_id) references  a(a_id)
);

#删除外键
alter table  b drop foreign key AB_id;


#增加外键
mysql> alter table `b`
    -> add constraint AB_id foreign key(fy_id) references  a(a_id);


B表中的fy_id 字段,只能添加 a_id中 已有的数据。

A表中a_id  被参照的数据, 不能被修改和删除

猜你喜欢

转载自www.cnblogs.com/mariobear/p/9180202.html
今日推荐