student(sno,sname,sage,ssex,sdept) course(cno,cname,credit,ctime) sc(sno,cno,grade) 1.建立学生表的insert触发器,若向学生表中插入一条记录,则自动向选课表中插入一行,令该生选一门选修人数最多的课。写sql语句
时间: 2024-01-07 07:05:35 浏览: 80
数据库实验报告论文.doc
假设选课表中有字段为 cno 和 num 的列,分别表示课程编号和选修人数。
以下是向学生表中插入记录时自动向选课表中插入一行的 SQL 语句:
```
CREATE TRIGGER insert_sc AFTER INSERT ON student
FOR EACH ROW
BEGIN
INSERT INTO sc (sno, cno, grade)
SELECT NEW.sno, cno, NULL
FROM course
WHERE cno = (
SELECT cno
FROM (
SELECT cno, COUNT(*) AS num
FROM sc
GROUP BY cno
ORDER BY num DESC
LIMIT 1
) AS t
);
UPDATE course
SET num = num + 1
WHERE cno = (
SELECT cno
FROM (
SELECT cno, COUNT(*) AS num
FROM sc
GROUP BY cno
ORDER BY num DESC
LIMIT 1
) AS t
);
END;
```
该触发器会在向学生表中插入记录时自动执行,向选课表中插入一行数据,使该学生选修人数最多的课程。同时,更新选修课程的选修人数。
阅读全文