当前位置:   article > 正文

SQL学习(七):怎么给一张表添加外键(四种方法)_sql为表中添加外键

sql为表中添加外键

如何添加外键

方法一:直接在属性值后面添加

create table score(
cscore int(11),
st_id int(50) references student(id),
cs_id int(30) references classes(id),
primary key(st_id,cs_id)
);

方法二:

create table score(
cscore int(11),
st_id int(50),
cs_id int(30),
primary key(st_id,cs_id),
FOREIGN KEY (st_id) REFERENCES student(id),
FOREIGN KEY (cs_id) REFERENCES classes(id)

);

方法三:添加约束

create table score(
cscore int(11),
st_id int(50),
cs_id int(30),
primary key(st_id,cs_id),
CONSTRAINT FK_ID_ST FOREIGN KEY (st_id) REFERENCES student(id),
CONSTRAINT FK_ID_CS FOREIGN KEY (cs_id) REFERENCES classes(id)·

);

方法四:在表的定义外进行添加

alter table 表名 add constraint FK_ID foreign key(你的外键字段名) REFERENCES 外表表名(对应的表的主键字段名);

参考:
https://www.cnblogs.com/qisong178878915/p/4435488.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/497430
推荐阅读
相关标签
  

闽ICP备14008679号