日期:2014-05-16  浏览次数:20592 次

添加外键
1.添加外键
有2个表
表stu
create table stu (id int primary key auto_increment,stuName varchar(20) not null,clazzId int not null);
表clazzId
create table clazz(clazzId primary key auto_increment,clazzName varchar(20) not null);

如果stu添加clazzId为外键,约束 constraint
alter table stu add constraint fk_stu_clazz foreign key(classId) references
clazz(classId);

2.级联操作
ON UPDATE CASCADE; 即在主表更新时,子表(们)产生连锁更新动作,似乎有些人喜欢把这个叫“级联”操作。:)
如果把这语句完整的写出来,就是:
alter table stu add constraint fk_stu_clazz foreign key(classId) references
clazz(classId) on update cascade;
除了 CASCADE 外,还有 RESTRICT(禁止主表变更)、SET NULL(子表相应字段设置为空)等操作。