1.建立学生表的insert触发器,若向学生表中插入一条记录,则自动向选课表中插入一行,令该生选一门选修人数最多的课。 2.在建立学生表的delete触发器,若选课表中该生有选课记录,则拒绝删除,要求在删除学生信息同时,将相关表中的信息全部删除。
时间: 2024-03-02 07:52:40 浏览: 65
14、为学生表创建触发器,要求: (1)当用户成功删除该表中的一条或多条记录时,触发器自动删
1. 建立学生表的insert触发器,实现自动选课功能:
```
CREATE TRIGGER insert_student_trigger
AFTER INSERT ON student
FOR EACH ROW
BEGIN
DECLARE max_count INT;
DECLARE max_course_id INT;
SELECT MAX(count), course_id INTO max_count, max_course_id FROM (
SELECT COUNT(*) AS count, course_id FROM select_course
GROUP BY course_id
) t;
INSERT INTO select_course (student_id, course_id) VALUES (NEW.student_id, max_course_id);
END;
```
2. 建立学生表的delete触发器,实现级联删除功能:
```
CREATE TRIGGER delete_student_trigger
BEFORE DELETE ON student
FOR EACH ROW
BEGIN
DECLARE has_select_course INT;
SELECT COUNT(*) INTO has_select_course FROM select_course WHERE student_id = OLD.student_id;
IF has_select_course > 0 THEN
DELETE FROM select_course WHERE student_id = OLD.student_id;
DELETE FROM student WHERE student_id = OLD.student_id;
END IF;
END;
```
以上是 MySQL 数据库的示例代码,实现的功能可能不太符合实际需求,仅供参考。在实际应用中,需要根据具体情况进行调整。
阅读全文