MySQL外键设置中的的 Cascade、NO ACTION、Restrict、SET NULL

   . cascade方式
在父表上update/delete记录时,同步update/delete掉子表的匹配记录 

   . set null方式
在父表上update/delete记录时,将子表上匹配记录的列设为null
要注意子表的外键列不能为not null  

   . No action方式
如果子表中有匹配的记录,则不允许对父表对应候选键进行update/delete操作  

   . Restrict方式
同no action, 都是立即检查外键约束

   . Set default方式
父表有变更时,子表将外键列设置成一个默认的值 但Innodb不能识别

DDL写法:

CREATE TABLE `scripts` (  
  `scriptid` bigint(20) unsigned NOT NULL,  
  `name` varchar(255) NOT NULL DEFAULT '',  
  `command` varchar(255) NOT NULL DEFAULT '',  
  `host_access` int(11) NOT NULL DEFAULT '2',  
  `usrgrpid` bigint(20) unsigned DEFAULT NULL,  
  `groupid` bigint(20) unsigned DEFAULT NULL,  
  `description` text NOT NULL,  
  `confirmation` varchar(255) NOT NULL DEFAULT '',  
  `type` int(11) NOT NULL DEFAULT '0',  
  `execute_on` int(11) NOT NULL DEFAULT '1',  
  PRIMARY KEY (`scriptid`),  
  KEY `scripts_1` (`usrgrpid`),  
  KEY `scripts_2` (`groupid`),  
  CONSTRAINT `c_scripts_1` FOREIGN KEY (`usrgrpid`) REFERENCES `usrgrp` (`usrgrpid`) ON DELETE CASCADE ON UPDATE CASCADE,  
  CONSTRAINT `c_scripts_2` FOREIGN KEY (`groupid`) REFERENCES `groups` (`groupid`)  
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  

转载自:http://blog.sina.com.cn/s/blog_91339bff0100ymc2.html

原文地址:https://www.cnblogs.com/vayci/p/7509463.html