mysql 触发器实现级联删除有外键的多张表

2019-10-12 10:17:44

1、数据,建表时有可能会报错,只需要把前三行注释删掉就行

-- ----------------------------
-- Table structure for tb_grade
-- ----------------------------
DROP TABLE IF EXISTS `tb_grade`;
CREATE TABLE `tb_grade` (
  `grade_id` int(11) NOT NULL AUTO_INCREMENT,
  `grade_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`grade_id`),
  UNIQUE KEY `grade_check` (`grade_name`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_grade
-- ----------------------------
INSERT INTO `tb_grade` VALUES (‘1‘, ‘一年级‘);
INSERT INTO `tb_grade` VALUES (‘2‘, ‘二年级‘);
INSERT INTO `tb_grade` VALUES (‘3‘, ‘三年级‘);
INSERT INTO `tb_grade` VALUES (‘4‘, ‘四年级‘);
INSERT INTO `tb_grade` VALUES (‘5‘, ‘五年级‘);

-- ----------------------------
-- Table structure for tb_subject
-- ----------------------------
DROP TABLE IF EXISTS `tb_subject`;
CREATE TABLE `tb_subject` (
  `subject_id` int(11) NOT NULL AUTO_INCREMENT,
  `subject_name` varchar(20) DEFAULT NULL,
  `class_hour` int(3) DEFAULT NULL,
  `grade_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`subject_id`),
  KEY `grade_id` (`grade_id`),
  CONSTRAINT `tb_subject_ibfk_1` FOREIGN KEY (`grade_id`) REFERENCES `tb_grade` (`grade_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_subject
-- ----------------------------
INSERT INTO `tb_subject` VALUES (‘1‘, ‘java‘, ‘60‘, ‘1‘);
INSERT INTO `tb_subject` VALUES (‘2‘, ‘html‘, ‘40‘, ‘1‘);
INSERT INTO `tb_subject` VALUES (‘3‘, ‘javascript‘, ‘30‘, ‘1‘);
INSERT INTO `tb_subject` VALUES (‘4‘, ‘database‘, ‘60‘, ‘2‘);
INSERT INTO `tb_subject` VALUES (‘5‘, ‘java oop‘, ‘60‘, ‘2‘);
INSERT INTO `tb_subject` VALUES (‘6‘, ‘servlet‘, ‘40‘, ‘2‘);
INSERT INTO `tb_subject` VALUES (‘7‘, ‘jsp‘, ‘40‘, ‘2‘);
INSERT INTO `tb_subject` VALUES (‘8‘, ‘struts2‘, ‘60‘, ‘3‘);
INSERT INTO `tb_subject` VALUES (‘9‘, ‘hibernate‘, ‘60‘, ‘3‘);
INSERT INTO `tb_subject` VALUES (‘10‘, ‘spring‘, ‘60‘, ‘3‘);

-- ----------------------------
-- Table structure for tb_student
-- ----------------------------
DROP TABLE IF EXISTS `tb_student`;
CREATE TABLE `tb_student` (
  `student_no` varchar(20) NOT NULL COMMENT ‘学号‘,
  `login_pwd` varchar(20) NOT NULL DEFAULT ‘123456‘ COMMENT ‘密码‘,
  `student_name` varchar(20) NOT NULL COMMENT ‘姓名‘,
  `sex` enum(‘女‘,‘男‘) DEFAULT ‘男‘ COMMENT ‘性别‘,
  `grade_id` int(11) DEFAULT NULL COMMENT ‘年级  - 外键‘,
  `phone` varchar(20) DEFAULT NULL COMMENT ‘联系电话‘,
  `address` varchar(100) DEFAULT ‘学生宿舍‘ COMMENT ‘现住址‘,
  `birthday` date DEFAULT NULL COMMENT ‘出生日期‘,
  `email` varchar(50) DEFAULT NULL COMMENT ‘电子邮件‘,
  PRIMARY KEY (`student_no`),
  KEY `grade_id` (`grade_id`),
  CONSTRAINT `tb_student_ibfk_1` FOREIGN KEY (`grade_id`) REFERENCES `tb_grade` (`grade_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_student
-- ----------------------------
INSERT INTO `tb_student` VALUES (‘s01‘, ‘123456‘, ‘宋江‘, ‘男‘, ‘1‘, ‘13888811111‘, ‘学生宿舍‘, ‘1985-10-10‘, ‘[email protected]‘);
INSERT INTO `tb_student` VALUES (‘s02‘, ‘123456‘, ‘卢俊义‘, ‘男‘, ‘1‘, ‘13888822222‘, ‘教场西路8号‘, ‘1987-08-08‘, ‘[email protected]‘);
INSERT INTO `tb_student` VALUES (‘s03‘, ‘123456‘, ‘吴用‘, ‘男‘, ‘2‘, ‘13888833333‘, ‘教场西路8号‘, ‘1991-06-06‘, ‘[email protected]‘);
INSERT INTO `tb_student` VALUES (‘s04‘, ‘123456‘, ‘孙二娘‘, ‘女‘, ‘2‘, ‘13888844444‘, ‘教场西路16号‘, ‘1983-05-05‘, ‘[email protected]‘);
INSERT INTO `tb_student` VALUES (‘s05‘, ‘123456‘, ‘李逵‘, ‘男‘, ‘1‘, ‘13888855555‘, ‘学生宿舍‘, ‘1992-01-01‘, ‘[email protected]‘);
INSERT INTO `tb_student` VALUES (‘s06‘, ‘123456‘, ‘顾大嫂‘, ‘女‘, ‘1‘, ‘13888866666‘, ‘教场西路16号‘, ‘1990-02-02‘, ‘[email protected]‘);
INSERT INTO `tb_student` VALUES (‘s07‘, ‘123456‘, ‘柴进‘, ‘男‘, ‘3‘, ‘13888877777‘, ‘学生宿舍‘, ‘1991-03-03‘, null);
INSERT INTO `tb_student` VALUES (‘s08‘, ‘123456‘, ‘林冲‘, ‘男‘, ‘3‘, ‘13888888888‘, ‘教场西路8号‘, ‘1986-04-04‘, null);
INSERT INTO `tb_student` VALUES (‘s09‘, ‘123456‘, ‘鲁智深‘, ‘男‘, ‘3‘, ‘13888899999‘, ‘教场西路8号‘, ‘1991-05-05‘, ‘‘);
INSERT INTO `tb_student` VALUES (‘s10‘, ‘123456‘, ‘扈三娘‘, ‘女‘, ‘2‘, ‘13888800000‘, ‘学生宿舍‘, ‘1983-06-06‘, ‘‘);

-- ----------------------------
-- Table structure for tb_score
-- ----------------------------
DROP TABLE IF EXISTS `tb_score`;
CREATE TABLE `tb_score` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT ‘成绩编号‘,
  `student_no` varchar(255) NOT NULL COMMENT ‘学号 - 外键‘,
  `subject_id` int(11) DEFAULT NULL COMMENT ‘所考科目‘,
  `student_score` float(5,2) DEFAULT ‘0.00‘ COMMENT ‘分数‘,
  `exam_date` date DEFAULT NULL COMMENT ‘考试日期‘,
  PRIMARY KEY (`id`),
  KEY `student_no` (`student_no`),
  KEY `subject_id` (`subject_id`),
  CONSTRAINT `tb_score_ibfk_1` FOREIGN KEY (`student_no`) REFERENCES `tb_student` (`student_no`),
  CONSTRAINT `tb_score_ibfk_2` FOREIGN KEY (`subject_id`) REFERENCES `tb_subject` (`subject_id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_score
-- ----------------------------
INSERT INTO `tb_score` VALUES (‘1‘, ‘s01‘, ‘1‘, ‘90.50‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘2‘, ‘s02‘, ‘1‘, ‘85.00‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘3‘, ‘s03‘, ‘1‘, ‘69.50‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘4‘, ‘s04‘, ‘1‘, ‘85.50‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘5‘, ‘s05‘, ‘1‘, ‘45.50‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘6‘, ‘s06‘, ‘1‘, ‘95.50‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘7‘, ‘s07‘, ‘1‘, ‘76.50‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘8‘, ‘s08‘, ‘1‘, ‘88.00‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘9‘, ‘s09‘, ‘1‘, ‘70.00‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘10‘, ‘s10‘, ‘1‘, ‘55.00‘, ‘2016-11-05‘);
INSERT INTO `tb_score` VALUES (‘11‘, ‘s01‘, ‘2‘, ‘80.50‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘12‘, ‘s02‘, ‘2‘, ‘70.00‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘13‘, ‘s03‘, ‘2‘, ‘68.50‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘14‘, ‘s04‘, ‘2‘, ‘82.50‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘15‘, ‘s05‘, ‘2‘, ‘43.50‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘16‘, ‘s06‘, ‘2‘, ‘90.50‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘17‘, ‘s07‘, ‘2‘, ‘70.50‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘18‘, ‘s08‘, ‘2‘, ‘80.00‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘19‘, ‘s09‘, ‘2‘, ‘80.00‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘20‘, ‘s10‘, ‘2‘, ‘56.00‘, ‘2016-11-07‘);
INSERT INTO `tb_score` VALUES (‘21‘, ‘s01‘, ‘3‘, ‘84.50‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘22‘, ‘s02‘, ‘3‘, ‘73.00‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘23‘, ‘s03‘, ‘3‘, ‘69.50‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘24‘, ‘s04‘, ‘3‘, ‘86.50‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘25‘, ‘s05‘, ‘3‘, ‘44.50‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘26‘, ‘s06‘, ‘3‘, ‘80.50‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘27‘, ‘s07‘, ‘3‘, ‘75.50‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘28‘, ‘s08‘, ‘3‘, ‘87.00‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘29‘, ‘s09‘, ‘3‘, ‘85.00‘, ‘2016-11-09‘);
INSERT INTO `tb_score` VALUES (‘30‘, ‘s10‘, ‘3‘, ‘66.00‘, ‘2016-11-09‘);

2、表结构

3、需求:针对数据库中的4张数据表(tb_grade、tb_subject、tb_student、tb_score)

在需要的数据表上创建触发器,达到每删除一个数据表的记录时都能顺顺利执行(级联删除)。

4、具体实现:

-- 为tb_grade创建触发器
DROP TRIGGER IF EXISTS trig_grade;
delimiter //
CREATE TRIGGER trig_grade BEFORE delete on tb_grade for each row
BEGIN
        DELETE FROM tb_student WHERE  grade_id = old.grade_id;
        DELETE FROM tb_subject WHERE grade_id = old.grade_id;
END //
delimiter ;

-- 为tb_student创建触发器
DROP TRIGGER IF EXISTS trig_student;
delimiter //
CREATE TRIGGER trig_student BEFORE delete on tb_student for each row
BEGIN
        DELETE FROM tb_score WHERE  student_no = old.student_no;
END //
delimiter ;

-- 为tb_subject创建触发器
DROP TRIGGER IF EXISTS trig_subject;
delimiter //
CREATE TRIGGER trig_subject BEFORE delete on tb_subject for each row
BEGIN
        DELETE FROM tb_score WHERE  subject_id = old.subject_id;
END //
delimiter ;

-- 查看此数据库中的触发器
SHOW TRIGGERS;

-- 测试删除数据是否能成功
DELETE FROM tb_student WHERE student_no = "S01";
DELETE FROM tb_grade WHERE grade_id = 1;
DELETE FROM tb_subject WHERE subject_id = 3;
DELETE FROM tb_score WHERE id = 9;

-- 最后可以查询表看看有没有被顺利删除

5、tb_score表是没有其他表将外键指向它的主键

想要删除从表的数据,需要先删除主表的数据

原文地址:https://www.cnblogs.com/zhangzimuzjq/p/11659842.html

时间: 2024-10-03 18:55:09

mysql 触发器实现级联删除有外键的多张表的相关文章

MySQL基础day03 存储引擎和外键MySQL 5.6

MySQL基础day03_存储引擎和外键-MySQL 5.6 外键的条件: 1,表的存储引擎为innodb存储引擎 2,表中外键字段的类型要与参考表的字段类型一致 3,外键字段要是索引类型中的一种 MySQL数据库的存储引擎 存储引擎:是mysql结构中的组成部分 mysql体系结构: 由8部分组成:连接池.Sql接口.分析器.优化器.缓存和缓冲.存储引擎.管理工具.物理存储设备 1.客户端:mysql 2.连接器: NativeC API 本地C语言接口.JDBCJAVA的数据库连接器.ODB

MySQL入门(alter语法 与 外键)

MySQL入门(三) 字段的修改.添加.与删除 修改表字段使用alter table语句,谨记! create table tf1( id int primary key auto_increment, x int, y int ); # 修改 alter table tf1 modify x char(4) default ''; alter table tf1 change y m char(4) default ''; # 增加 mysql>: alter table 表名 add 字段名

删除带外键的表【foreign key constraint fails】报错

title: 删除带外键的表[foreign key constraint fails]报错 date: 2018-08-02 21:59:06 tags: 数据库 --- 遥想当时正在学hibernate的时候,刚好学到了一对多,多对多的关联操作.时间也正是刚好在那是有了一个项目,把各表的间的结构还理清,俗话说学到就要用到,就把这些表的结构都能配置级联关系的都把它配上.没想到就在这里给自己放了个小坑.前几天在一个帖子中看到别人说,尽量少配些ORM约束,数据库的外键约束什么的.当时还不以为然.没

sql中批量删除带有外键的所有表

1首先删除所有的外检约束 --删除所有外键约束 DECLARE c1 cursor forselect 'alter table ['+ object_name(parent_obj) + '] drop constraint ['+name+']; 'from sysobjectswhere xtype = 'F'open c1declare @c1 varchar(8000)fetch next from c1 into @c1while(@@fetch_status=0)beginexec

Oracle怎么查外键建在哪个表上

怎样查外键建在哪个表上 有时候删除某张表记录的时候,会报错外键约束不能删除. 如果不了解表之间的关系,可以通过以下语句查询到外键是建在哪张表上的: select * from dba_constraints where constraint_name='xxx' and constraint_type = 'R'; 例如:我的程序日志中报如下错误,我要知道外键是在那个表上. 2015-09-08 18:28:18 [ main:261597003 ] - [ ERROR ] java.sql.S

使用truncate ,截断有外键约束的父表

此时有两种方法,解决1.删除外键约束,删除该表,在重建外键约束--查询外键约束select TABLE_NAME,CONSTRAINT_NAME,CONSTRAINT_TYPE,R_CONSTRAINT_NAME from ALL_CONSTRAINTS WHERE constraint_type='R' and owner='SCOTT'; 删掉外键约束 alter table emp drop constraint fk_deptno; truncate  表后如果仍然想要关联原来的子表,重

从MySQL全库备份中恢复某个库和某张表【转】

从MySQL全库备份中恢复某个库和某张表 一.全库备份-A [[email protected] backup]#mysqldump -uroot -p123456 --default-character-set=utf8 --single-transaction --extended-insert=false --hex-blob --master-data=2 --log-error=/tmp/test.err --routines --triggers --events --quick -

MySQL 如何删除有外键约束的表数据

-- 禁用外键约束 SET FOREIGN_KEY_CHECKS=0; -- 删除数据 truncate table stockTBL; -- 启动外键约束 SET FOREIGN_KEY_CHECKS=1; -- 查看当前FOREIGN_KEY_CHECKS的值,可用如下命令: SELECT @@FOREIGN_KEY_CHECKS;

如何删除有外键约束的数据

SQLServer 2012 表TableA与TbaleB有外键约束,约束列名为TbaleB的iTableAID列,删除的时候会提示 DELETE  dbo.TableA 消息 547,级别 16,状态 0,第 1 行 DELETE 语句与 REFERENCE 约束"FK_TbaleB_TableA_iTableAID"冲突.该冲突发生于数据库"TEST",表"dbo.TbaleB", column 'iTableAID'. 语句已终止. 此时需