mysql外键设置方式

mysql外键设置方式/在创建索引时,可指定在delete/update父表时,对子表进行的相应操作,
包括: restrict, cascade,set null 和 no action ,set default.

  • restrict,no action:
    立即检查外键约束,如果子表有匹配记录,父表关联记录不能执行 delete/update 操作;

  • cascade:
    父表delete /update时,子表对应记录随之 delete/update ;

  • set null:
    父表在delete /update时,子表对应字段被set null,此时留意子表外键不能设置为not null ;

  • set default:
    父表有delete/update时,子表将外键设置成一个默认的值,但是 innodb不能识别,实际mysql5.5之后默认的存储引擎都是innodb,所以不推荐设置该外键方式。如果你的环境mysql是5.5之前,默认存储引擎是myisam,则可以考虑。

选择set null ,setdefault,cascade 时要谨慎,可能因为错误操作导致数据丢失。

如果以上描述并不能理解透彻,可以参看下面例子。

country 表是父表,country_id是主键,city是子表,外键为country_id,和country表的主键country_id对应。

create table country(
	country_id smallint unsigned not null auto_increment,
	country varchar(50) not null,
	last_update timestamp not null default current_timestamp on update current_timestamp,
	primary key(country_id)
)engine=INNODB default charset=utf8;

CREATE TABLE `city` (
  `city_id` smallint(5) unsigned NOT NULL auto_increment,
  `city` varchar(50) NOT NULL,
  `country_id` smallint(5) unsigned NOT NULL,
  `last_update` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  PRIMARY KEY  (`city_id`),
  KEY `idx_fk_country_id` (`country_id`),
  CONSTRAINT `fk_city_country` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`)  on delete restrict   ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这里写图片描述
这里写图片描述

例如对上面新建的两个表,子表外键指定为:on delete restrict ON UPDATE CASCADE 方式,在主表删除记录的时候,若子表有对应记录,则不允许删除;主表更新记录时,如果子表有匹配记录,则子表对应记录 随之更新。
eg:

insert into country values(1,'wq',now());
select * from country;
insert into city values(222,'tom',1,now());
select * from city;

这里写图片描述

delete from country where country_id=1;
update country set country_id=100 where country_id=1;
select * from country where country='wq';
select * from city where city='tom';

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值