mysql中外键的做用

外键的好处:html

可使得两张表关联,保证数据的一致性和实现一些级联操做;spa


/*==============================================================*/.net

/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2017\10\18 星期三 11:36:35                      */
/*==============================================================*/


drop table if exists A;

drop table if exists B;

/*==============================================================*/
/* Table: A                                                     */
/*==============================================================*/
create table A
(
   id                   int(11) not null,
   name                 varchar(255),
   primary key (id)
);

/*==============================================================*/
/* Table: B                                                     */
/*==============================================================*/
create table B
(
   bid                  int(25) not null,
   id                   int(11),
   adress               varchar(255),
   primary key (bid)
);

alter table B add constraint FK_Reference_1 foreign key (id)

      references A (id) on delete restrict on update restrict;rest

案例操做一:htm

select * from ablog

id     nameit

111   henanio

222    jiantable

select * from bclass

bid  id    adres

14   222   东北


insert into  b values(15,333,'beijing');

[SQL] insert into  b values(15,333,'beijing');
[Err] 1452 - Cannot add or update a child row: a foreign key constraint fails (`db_ljf`.`b`, CONSTRAINT `FK_Reference_1` FOREIGN KEY (`id`) REFERENCES `a` (`id`))

提示:小子,想造反呀!你还没大哥呢!

案例二:

delete from a  where id=222

[SQL] delete from a  where id=222

[Err] 1451 - Cannot delete or update a parent row: a foreign key constraint fails (`db_ljf`.`b`, CONSTRAINT `FK_Reference_1` FOREIGN KEY (`id`) REFERENCES `a` (`id`))

提示:有外键约束,且为Restrict当取值为No Action或者Restrict时,则当在父表(即外键的来源表)中删除对应记录时,首先检查该记录是否有对应外键,若是有则不容许删除。

提示:不行呀,有约束的,大哥下面还有小弟,可不能扔下咱们无论呀!

http://www.jb51.net/article/90729.htm

案例三:

delete from b  where bid=14

select * from b

bid id adress


select * from a




MySQL外键约束On Delete、On Update各取值的含义

 

先看On Delete属性,可能取值如上图为:No Action, Cascade,Set Null, Restrict属性。

当取值为No Action或者Restrict时,则当在父表(即外键的来源表)中删除对应记录时,首先检查该记录是否有对应外键,若是有则不容许删除。

当取值为Cascade时,则当在父表(即外键的来源表)中删除对应记录时,首先检查该记录是否有对应外键,若是有则也删除外键在子表(即包含外键的表)中的记录。

当取值为Set Null时,则当在父表(即外键的来源表)中删除对应记录时,首先检查该记录是否有对应外键,若是有则设置子表中该外键值为null(不过这就要求该外键容许取null)。




当取值为No Action或者Restrict时,则当在父表(即外键的来源表)中更新对应记录时,首先检查该记录是否有对应外键,若是有则不容许更新。

当取值为Cascade时,则当在父表(即外键的来源表)中更新对应记录时,首先检查该记录是否有对应外键,若是有则也更新外键在子表(即包含外键的表)中的记录。

当取值为Set Null时,则当在父表(即外键的来源表)中更新对应记录时,首先检查该记录是否有对应外键,若是有则设置子表中该外键值为null(不过这就要求该外键容许取null)。

http://blog.sina.com.cn/s/blog_5d359d310100w5mb.html