外键:
连接多张表之间的关系,建立外键后,一张表的内容要完全匹配另一张有关联关系的表
建表时添加外键约束:
create table stu(
sid int primary key auto_increment,
sname varchar(20) unipue not null,
id_p int
);
CREATE TABLE Orders(
Id_O int NOT NULL,
OrderNo int NOT NULL,
Id_P int,
PRIMARY KEY (Id_O),
FOREIGN KEY (Id_P) REFERENCES stu(Id_P)
);
alt
表外 添加外键约束:
alter table t_detail add foreign key (sid) references t_stu(sid) ;
alter table t_detail add foreign key (subID) references t_sub(subID);
ALTER TABLE t_sub add constraint 外键名 foreign key(tid) references t_teacher(tid);
取消外键约束:
alter table t_sub drop foreign key 外键名;
级联操作
加外键约束时 在最后 写
on delete cascade(在级联删除)
on update cascade.(在级联更新)
注意: 外键名字 不能相同 , 因为 数据库底层会存储 外键关系.