请选择 进入手机版 | 继续访问电脑版

mysql命令代码:创建表的时候添加外键

[复制链接]
查看2124 | 回复0 | 2020-10-12 07:13 | 显示全部楼层 |阅读模式
mysql命令代码:创建表的时候添加外键
  1. drop table if exists stuinfo;
  2. create table stuinfo(
  3.        id tinyint primary key,
  4.        name varchar(20)
  5. )engine=innodb;

  6. drop table if exists stuscore;
  7. create table stuscore(
  8.        sid tinyint primary key,
  9.        score tinyint unsigned,
  10.        foreign key(sid) references stuinfo(id)   -- 创建外键
  11. )engine=innodb;
复制代码
通过修改表的时候添加外键
语法:alter table 从表 add foreign key(公共字段) references 主表(公共字段)
案例代码如下:
  1. drop table if exists stuinfo;
  2. create table stuinfo(
  3.        id tinyint primary key,
  4.        name varchar(20)
  5. )engine=innodb;

  6. drop table if exists stuscore;
  7. create table stuscore(
  8.        sid tinyint primary key,
  9.        score tinyint unsigned
  10. )engine=innodb;

  11. alter table stuscore add foreign key (sid) references stuinfo(id)
复制代码

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

UID
1
贡献
387
丢币
38902
主题
4607
回帖
116
注册时间
2018-9-25
最后登录
2024-3-30