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

mysql数据库操作之外键(foreign key)

[复制链接]
查看1603 | 回复0 | 2020-9-30 09:55 | 显示全部楼层 |阅读模式
外键:从表中的公共字段
  1. -- 创建表的时候添加外键
  2. drop table if exists stuinfo;
  3. create table stuinfo(
  4.        id tinyint primary key,
  5.        name varchar(20)
  6. )engine=innodb;

  7. drop table if exists stuscore;
  8. create table stuscore(
  9.        sid tinyint primary key,
  10.        score tinyint unsigned,
  11.        foreign key(sid) references stuinfo(id)   -- 创建外键
  12. )engine=innodb;

  13. -- 通过修改表的时候添加外键
  14. 语法:alter table 从表 add foreign key(公共字段) references 主表(公共字段)

  15. drop table if exists stuinfo;
  16. create table stuinfo(
  17.        id tinyint primary key,
  18.        name varchar(20)
  19. )engine=innodb;

  20. drop table if exists stuscore;
  21. create table stuscore(
  22.        sid tinyint primary key,
  23.        score tinyint unsigned
  24. )engine=innodb;

  25. alter table stuscore add foreign key (sid) references stuinfo(id)
复制代码
删除外键
  1. 通过外键的名字删除外键
复制代码
  1. -- 删除外键
  2. mysql> alter table stuscore drop foreign key `stuscore_ibfk_1`;
  3. Query OK, 0 rows affected (0.00 sec)
  4. Records: 0  Duplicates: 0  Warnings: 0
复制代码
小结:
1、只有innodb才能支持外键2、公共字段的名字可以不一样,但是数据类型要一样

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

本版积分规则

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