我有三个3个表(类,模块,module_classes),为简单起见,它们如下: 班级表:
+-----+---------+----------+-----------+-----------+
| id | name | level | deleted |create_time|
+-----|---------+----------|-----------+-----------+
|1 | C1 |4 | 1 |some date |
|2 | C2 |2 | 0 |some date |
|3 | C1 |1 | 0 |some date |
+-----+---------+----------+-----------+-----------+
模块表:
+-----+---------+----------+
| id | name | deleted |
+-----|---------+----------|
|1 | M1 |0 |
|2 | M2 |0 |
|3 | M1 |0 |
+-----+---------+----------+
module_class表:
+-----+---------+----------+
| id | classId | moduleId |
+-----|---------+----------|
|1 | 1 |1 |
|2 | 2 |2 |
|3 | 1 |3 |
+-----+---------+----------+
每学期一级增加一级,4学期后该类将被设置为删除,并且将插入具有相同名称但级别为1的新类,模块将保持不变,module_class中的类ID必须为从已删除的更新到插入的类,因此必须如下所示:
+-----+---------+----------+
| id | classId | moduleId |
+-----|---------+----------|
|1 | 3 |1 |
|2 | 2 |2 |
|3 | 3 |3 |
+-----+---------+----------+
我无法想象如何使它成为可能,任何关于如何做到这一点的建议?提前谢谢
答案 0 :(得分:0)
尝试此触发器
DROP TRIGGER IF EXISTS TRIGGER_class_UPDATE;
DELIMITER $$
CREATE TRIGGER TRIGGER_class_UPDATE BEFORE UPDATE ON class FOR EACH ROW BEGIN
SET @moduleId= (SELECT moduleId FROM module_class WHERE class_id=old.id);
IF NEW.level=4 THEN
SET NEW.deleted=1;
INSERT INTO class(name,level,deleted,create_time) values (old.name,1,0,now());
set @newclassid=(SELECT ID FROM class WHERE name=old.anem and deleted=0 and level=old.level);
INSERT INTO module_class(classId,moduleId) values (@newclassid,@moduleId);
ELSE
SET NEW.deleted=0;
END IF;
END$$
DELIMITER ;