外键:从表中的公共字段
- -- 创建表的时候添加外键
- 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)
复制代码 删除外键
- -- 删除外键
- mysql> alter table stuscore drop foreign key `stuscore_ibfk_1`;
- Query OK, 0 rows affected (0.00 sec)
- Records: 0 Duplicates: 0 Warnings: 0
复制代码 小结:
1、只有innodb才能支持外键2、公共字段的名字可以不一样,但是数据类型要一样
|
|