请给我举一个例子,mysql创建一个过程,统计选课表(mess_xk)中每门课程的选课人数及平均成绩。请举一个完整的例子,代码要求新手入门mysql.
时间: 2024-03-24 09:41:20 浏览: 53
好的,以下是一个例子:
首先,我们需要创建一个存储过程来实现这个功能。打开MySQL命令行或者使用MySQL客户端,输入以下代码:
```
DELIMITER $$
CREATE PROCEDURE `course_statistics`()
BEGIN
DECLARE course_name CHAR(50);
DECLARE total_selected INT;
DECLARE avg_score FLOAT;
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR SELECT DISTINCT course_name FROM mess_xk;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
CREATE TEMPORARY TABLE temp_table (
course_name CHAR(50),
total_selected INT,
avg_score FLOAT
);
OPEN cur;
read_loop: LOOP
FETCH cur INTO course_name;
IF done THEN
LEAVE read_loop;
END IF;
SELECT COUNT(*) INTO total_selected FROM mess_xk WHERE course_name = course_name;
SELECT AVG(score) INTO avg_score FROM mess_xk WHERE course_name = course_name;
INSERT INTO temp_table (course_name, total_selected, avg_score) VALUES (course_name, total_selected, avg_score);
END LOOP;
CLOSE cur;
SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
END$$
DELIMITER ;
```
然后,我们就可以调用这个存储过程来统计选课表中每门课程的选课人数及平均成绩了。输入以下代码:
```
CALL course_statistics();
```
执行之后,就会输出每门课程的选课人数及平均成绩。
阅读全文