mysql命令代码:创建表的时候添加外键
- drop table if exists stuinfo;
- create table stuinfo(
- id tinyint primary key,
- name varchar(20)
- )engine=innodb;
- drop table if exists stuscore;
- create table stuscore(
- sid tinyint primary key,
- score tinyint unsigned,
- foreign key(sid) references stuinfo(id) -- 创建外键
- )engine=innodb;
复制代码 通过修改表的时候添加外键
语法:alter table 从表 add foreign key(公共字段) references 主表(公共字段)
案例代码如下:
- drop table if exists stuinfo;
- create table stuinfo(
- id tinyint primary key,
- name varchar(20)
- )engine=innodb;
- drop table if exists stuscore;
- create table stuscore(
- sid tinyint primary key,
- score tinyint unsigned
- )engine=innodb;
- alter table stuscore add foreign key (sid) references stuinfo(id)
复制代码
|
|