单学号: (1) 在学生表中增加一个“avgGrade”字段记录学生的平均成绩,并更新avgGrade属性的值; (2) 创建一个触发器,当输入学生选课成绩时,更新其平均成绩;并使用SQL语句往tb_sc表插入学生选课成绩记录,给出触发器触发后的相应结果。 双学号: (1) 在学生表中增加一个“TCredit”字段记录学生选课的总学分,并更新TCredit属性的值; (2) 创建一个触发器,当输入学生选课成绩时,如果成绩大于等于60分则将该课程的学分计入总学分;并使用SQL语句往tb_sc表插入学生选课成绩记录,给出触发器触发后的相应结果。
时间: 2024-03-08 22:51:03 浏览: 79
单学号:
1) 在学生表中增加一个“avgGrade”字段记录学生的平均成绩,并更新avgGrade属性的值:
```sql
ALTER TABLE tb_student ADD COLUMN avgGrade FLOAT;
UPDATE tb_student SET avgGrade = (SELECT AVG(score) FROM tb_sc WHERE tb_sc.sid = tb_student.sid);
```
2) 创建一个触发器,当输入学生选课成绩时,更新其平均成绩:
```sql
CREATE TRIGGER tr_tb_sc AFTER INSERT ON tb_sc
FOR EACH ROW
BEGIN
UPDATE tb_student SET avgGrade = (SELECT AVG(score) FROM tb_sc WHERE tb_sc.sid = NEW.sid) WHERE sid = NEW.sid;
END;
```
3) 往tb_sc表插入学生选课成绩记录:
```sql
INSERT INTO tb_sc (sid, cid, score) VALUES (1001, 1, 90);
-- 触发器会更新学生1001的平均成绩
SELECT * FROM tb_student WHERE sid = 1001;
```
输出结果为:
| sid | sname | sex | age | nation | avgGrade |
| --- | ----- | --- | --- | ------ | -------- |
| 1001 | 张三 | 男 | 20 | 汉族 | 90 |
双学号:
1) 在学生表中增加一个“TCredit”字段记录学生选课的总学分,并更新TCredit属性的值:
```sql
ALTER TABLE tb_student ADD COLUMN TCredit INT;
UPDATE tb_student SET TCredit = (SELECT SUM(credit) FROM tb_course WHERE cid IN (SELECT cid FROM tb_sc WHERE tb_sc.sid = tb_student.sid AND score >= 60));
```
2) 创建一个触发器,当输入学生选课成绩时,如果成绩大于等于60分则将该课程的学分计入总学分:
```sql
CREATE TRIGGER tr_tb_sc AFTER INSERT ON tb_sc
FOR EACH ROW
BEGIN
IF NEW.score >= 60 THEN
UPDATE tb_student SET TCredit = TCredit + (SELECT credit FROM tb_course WHERE cid = NEW.cid) WHERE sid = NEW.sid;
END IF;
END;
```
3) 往tb_sc表插入学生选课成绩记录:
```sql
INSERT INTO tb_sc (sid, cid, score) VALUES (1001, 1, 90);
-- 触发器会将该课程的学分计入学生1001的总学分
SELECT * FROM tb_student WHERE sid = 1001;
```
输出结果为:
| sid | sname | sex | age | nation | TCredit |
| --- | ----- | --- | --- | ------ | ------- |
| 1001 | 张三 | 男 | 20 | 汉族 | 4 |
阅读全文