当前位置:   article > 正文

数据库SQL语句:给表添加外键的四种方式_sql添加外键

sql添加外键

1. 创建表的同时添加外键

  1. create table score(
  2. score int(3),
  3. st_id int(16),
  4. cs_id int(16),
  5. primary key(st_id,cs_id),
  6. FOREIGN KEY (st_id) REFERENCES student(id),
  7. FOREIGN KEY (cs_id) REFERENCES classes(id)
  8. );

2. 已经创建表了怎么办:在表的定义外进行添加

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

3.直接在属性值后面添加

  1. create table score(
  2. cscore int(11),
  3. st_id int(50) references student(id),
  4. cs_id int(30) references classes(id),
  5. primary key(st_id,cs_id)
  6. );

4.添加约束

  1. create table score(
  2. cscore int(11),
  3. st_id int(50),
  4. cs_id int(30),
  5. primary key(st_id,cs_id),
  6. CONSTRAINT `FK_ID_ST` FOREIGN KEY (st_id) REFERENCES student(id),
  7. CONSTRAINT `FK_ID_CS` FOREIGN KEY (cs_id) REFERENCES classes(id)
  8. );

参考:sql增删改查基本语句 - 百度文库

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

闽ICP备14008679号