student(sno,sname,sage,ssex,sdept) course(cno,cname,credit,ctime) sc(sno,cno,grade) 1.建立学生表的insert触发器,若向学生表中插入一条记录,则自动向选课(sc)表中插入一行,令该生选一门选修人数最多的课。写sql语句
时间: 2024-03-02 20:52:06 浏览: 53
数据库实验报告论文.doc
以下是向学生表中插入记录时自动向选课表中插入一行的 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 (
SELECT cno, COUNT(*) AS num
FROM sc
GROUP BY cno
ORDER BY num DESC
LIMIT 1
) AS t
WHERE cno NOT IN (
SELECT cno
FROM sc
WHERE sno = NEW.sno
);
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;
```
该触发器会在向学生表中插入记录时自动执行,向选课表中插入一行数据,使该学生选修人数最多的尚未选修的课程。同时,更新选修课程的选修人数。
阅读全文