程序媛计划——mysql外键

本文介绍了数据库中外键的概念及其实现方式,并通过实例演示了如何在外键约束下进行级联删除和更新操作。

定义

外键:如果一个表的某个字段指向另一个表的主键,就称之为外键。被指向的表,称之为主表,也叫父表,那么另一个表就是从表,也叫子表

 

#先新建两个表

mysql> create table author_table(
    -> author_id int(4) not null primary key auto_increment,
    -> author_name char(20) not null);
Query OK, 0 rows affected (0.02 sec)
mysql> create table article_table(
    -> article_id int(4) not null primary key auto_increment,
    -> article_title char(20) not null,
    -> author_id int(4) not null,
    -> foreign key(author_id) references author_table(author_id));  #这一步使得article_table中的author_id字段成为外键
Query OK, 0 rows affected (0.02 sec)

#添加数据

mysql> insert into author_table values
    -> (1,'zhao'),
    -> (2,'qian'),
    -> (3,'sun'),
    -> (4,'li');
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0
mysql> insert into article_table values
    -> (1001,'c++',1),
    -> (1002,'java',1),
    -> (1003,'python',2),
    -> (1004,'mysql',3),
    -> (1005,'jacascript',4);
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

 

#子表和附表之间的约束

0 article_table中不能添加author_id为5的记录;

1 author_table中不能删除author_id为4的记录,因为子表中还有作者4的文章

 

#删除外键约束

mysql> alter table article_table drop foreign key article_table_ibfk_1;
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0

 

#级联操作

#添加外键

mysql> alter table article_table
    -> add foreign key fk_id(author_id)  #这里fk_id可以自己指定
    -> references author_table(author_id)
    -> on delete cascade  #cascade表示关联操作。子表会依赖父表中的数据关联删除或更新
    -> on update cascade;    
Query OK, 5 rows affected (0.02 sec)
Records: 5  Duplicates: 0  Warnings: 0

 

#set null关键字

set null,表示子表数据不指向父表任何记录。当不加set null和cascade时,默认为restrict(拒绝主表的相关操作),所以开始主表无法删除数据

 

转载于:https://www.cnblogs.com/IcarusYu/p/7533482.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值