mysql修改student表,添加一个字段班号,数据类型为varchar(10),创建一个班级表class(班号,所在系,专业,人数),数据类型自定,并录入一定的数据。利用触发器实现:向student表添加一行数据,班级表中对应班级的人数加一,向student表中删除一行数据,班级表中对应班级的人数减一
时间: 2024-03-19 15:43:14 浏览: 307
好的,我来回答你的问题。
首先,以下是修改 `student` 表和创建 `class` 表的 SQL 语句:
```sql
-- 修改 student 表,添加班号字段
ALTER TABLE student ADD COLUMN class_id VARCHAR(10);
-- 创建 class 表
CREATE TABLE class (
class_id VARCHAR(10) PRIMARY KEY,
department VARCHAR(20),
major VARCHAR(20),
student_num INT
);
```
然后,我们需要创建两个触发器,一个用于在插入数据时更新班级表的人数,另一个用于在删除数据时更新班级表的人数。
```sql
-- 创建触发器,当向 student 表中插入数据时,班级表对应班级的人数加一
CREATE TRIGGER add_student_num AFTER INSERT ON student
FOR EACH ROW
BEGIN
UPDATE class SET student_num = student_num + 1 WHERE class_id = NEW.class_id;
END;
-- 创建触发器,当从 student 表中删除数据时,班级表对应班级的人数减一
CREATE TRIGGER reduce_student_num AFTER DELETE ON student
FOR EACH ROW
BEGIN
UPDATE class SET student_num = student_num - 1 WHERE class_id = OLD.class_id;
END;
```
这样,当你向 `student` 表中添加一行数据时,班级表中对应班级的人数会自动加一;当你删除 `student` 表中的一行数据时,班级表中对应班级的人数会自动减一。
希望这个回答能够帮到你,如果还有其他问题请随时问我。
阅读全文
相关推荐


















