sql中怎样创建外键约束

create table yuangong
(
编号 char(8) not null primary key,
姓名 char(8) not null,
性别 char(2) null,
出生日期 datetime null,
职称 char(10),
职务 char(10),
部门号 char(2) constraint fk_bumenhao foreign key(部门号) references bumen(部门号)
)

create table bumen
(
部门号 char(2) not null primary key,
部门名称 char(12) not null
)

create table gongzi
(
编号 char(8) not null primary key,
收入 money null,
支出 money null
)
怎样在yuangong表中创建外键约束

添加外键 ,alter table B

语法:alter table 表名 add constraint 外键约束名 foreign key(列名) references 引用外键表(列名) 

如: 

alter table Stu_PkFk_Sc 
add constraint Fk_s 
foreign key (sno) 
references Stu_PkFk_S(sno)

--cc是外键约束名,不能重复,也不能是int类型(如1,2,3)

add constraint cc

--B表里的需要约束的字段(id)

foreign key (id)

--A表后的(id)可省略

references A (id)

扩展资料:

数据查询语言,其语句,也称为“数据检索语句”,用以从表中获得数据,确定数据怎样在应用程序给出。保留字SELECT是DQL(也是所有SQL)用得最多的动词,其他DQL常用的保留字有WHERE,ORDER BY,GROUP BY和HAVING。这些DQL保留字常与其他类型的SQL语句一起使用。

参考资料:结构化查询语言_百度百科

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-10-11

添加外键 ,alter table B

语法:alter table 表名 add constraint 外键约束名 foreign key(列名) references 引用外键表(列名) 

如: 

alter table Stu_PkFk_Sc 
add constraint Fk_s 
foreign key (sno) 
references Stu_PkFk_S(sno)

--cc是外键约束名,不能重复,也不能是int类型(如1,2,3)

add constraint cc

--B表里的需要约束的字段(id)

foreign key (id)

--A表后的(id)可省略

references A (id)

第2个回答  2011-10-24
在创建表之后,添加外键约束:
alter table yuangong add constraint fk foreign key (部门号) references bumen(部门号)
或者在创建表的时候添加外键
foreign key (部门号) references bumen(部门号)放在最后,用","与列分隔
第3个回答  2019-05-28
alter table 从表 表名 add constraint FK_ID foreign key(外键字段名)references 主表表名(主键字段名)这样就为表添加了一个外键约束。
第4个回答  2019-12-22
怎样创建外键约束在寸步不让你走路的地方灌渠桥