[进阶]MySQL学习笔记四数据表外键ForeignKey

     外键的创建使得两张数据表产生关联,通过外键关系,可以检索到表1外键指向对应的表2的记录。
     表1的外键可以指向表2的 主键或者unique列
     
     一、创建数据表时添加外键关联
     
     1. 创建班级数据表
     create table Class(
          Id int not null auto_increment,
          No int not null,
          Name varchar(50) default '',
          primary key (Id),
          unique(No)
     );
  • No: 班级号,作为Student的外键所关联的键,必须是unique或者primary的,否则会出现“ERROR 1215 (HY000): Cannot add foreign key constraint

     2. 创建学生数据表
     create table Student(
          Id int not null auto_increment, 
          Name varchar(50),
          ClassNo int not null,
          primary key (Id),
          foreign key (ClassNo) references Class(No)
     );
  • ClassNo: 关联Class表的No列
    

     二、重命名/删除数据表的外键

     1. 重命名
     alter table student
     add constraint fk_student_classno
     foreign key (classno) references class (no);
     
     2. 删除
     alter table student
     drop foreign key fk_student_classno;

    
     
          
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值