一、先建表,再追加约束(不推荐)
基本语法:alter table 表名 约束名 约束类型 (字段);
例如:
添加主键约束:
alter table students PK_S_ID primary key (id); /*PK_S_ID 表示约束名*/
添加外键约束:
alter table 字表名 FK_S_字表_字段 foreign key (外键字段) references 父表名 (父表主键);
二、建表时添加(推荐使用)
create table sts(
id int not null,
studentsId int not null,
constraint FK_M_P foreign key(studentsId) references students(Id) /*添加外键*/
);
建表时,子表添加外键的语法:
constraint 键名 foreign key(外键字段) references 父表(父表主键)