1.新建学生成绩表score 新建学生表student ;成绩表字段:科目,分数;学生表字段:名称,年龄; 2.用存储过程添加10名学生和4个科目,40条记录成绩’3.从2020年6月20号 18点开始每10分钟添加1名学生以及他四个科目的成绩
时间: 2024-03-01 20:50:56 浏览: 79
创建成绩表score-使用PLSQL语句对表中数据进行更新
好的,针对您的问题,我可以给出以下 SQL 代码实现您的需求:
首先,创建学生成绩表 score 和学生表 student:
```sql
CREATE TABLE score (
id INT AUTO_INCREMENT PRIMARY KEY,
subject VARCHAR(20),
score INT,
student_id INT,
FOREIGN KEY (student_id) REFERENCES student(id)
);
CREATE TABLE student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20),
age INT
);
```
然后,创建存储过程 add_stu_score,用于添加学生和成绩记录:
```sql
DELIMITER //
CREATE PROCEDURE add_stu_score()
BEGIN
DECLARE i INT DEFAULT 1;
DECLARE stu_name VARCHAR(20);
DECLARE stu_age INT;
DECLARE subject VARCHAR(20);
DECLARE score INT;
WHILE i <= 10 DO
SET stu_name = CONCAT('Student_', i);
SET stu_age = FLOOR(RAND() * 10 + 15); -- 随机生成15~24岁的年龄
INSERT INTO student (name, age) VALUES (stu_name, stu_age);
SET @student_id = LAST_INSERT_ID(); -- 获取插入的学生记录的id
SET subject = 'Subject_1';
SET score = FLOOR(RAND() * 60 + 40); -- 随机生成40~99的分数
INSERT INTO score (subject, score, student_id) VALUES (subject, score, @student_id);
SET subject = 'Subject_2';
SET score = FLOOR(RAND() * 60 + 40);
INSERT INTO score (subject, score, student_id) VALUES (subject, score, @student_id);
SET subject = 'Subject_3';
SET score = FLOOR(RAND() * 60 + 40);
INSERT INTO score (subject, score, student_id) VALUES (subject, score, @student_id);
SET subject = 'Subject_4';
SET score = FLOOR(RAND() * 60 + 40);
INSERT INTO score (subject, score, student_id) VALUES (subject, score, @student_id);
SET i = i + 1;
SELECT CONCAT(stu_name, '的成绩已添加') AS message;
SELECT SLEEP(600); -- 暂停10分钟
END WHILE;
END //
DELIMITER ;
```
最后,运行以下 SQL 代码,调用 add_stu_score 存储过程,从2020年6月20号 18点开始每10分钟添加1名学生以及他四个科目的成绩:
```sql
SET GLOBAL event_scheduler = ON; -- 先启用事件调度器
CREATE EVENT add_stu_score_event
ON SCHEDULE EVERY 10 MINUTE
STARTS '2020-06-20 18:00:00'
DO
CALL add_stu_score();
```
这样,每10分钟就会添加一名学生以及他四个科目的成绩记录,直到添加完10名学生为止。注意,在使用存储过程和事件调度器时,请确保您的 MySQL 版本支持这些功能。
阅读全文