关联A表的某个字段关联B表的某个主键字段,
叫外键约束(主外键关联) ,A表的那个字段叫外键
1.建表时:
create table tbl_name2(
column_name1 char(2) not null,
column_name2 char(2) not null,
constraint fk_name FOREIGN KEY(column_name) REFERENCES tbl_name(colum_name2) ON DELETE CASCADE
);
ON DELETE CASCADE:设置级联删除,当主键的字段被删除时,外键所对应的字段也同时被删除,看需求添加
2.建表后:
ALTER TABLE tbl_name ADD CONSTRIANTS fk_name FOREIGN KEY(column_name) REFERENCES tbl_name2(column_name2)
ON DELETE CASCADE;
(小写的是可以修改的)
删除外键约束:
alter table tbl_name drop constraints fk_name;