我有以下表格
相册:
+----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+-------------+------+-----+---------+----------------+
| album_id | int(11) | NO | PRI | NULL | auto_increment |
| band_id | int(11) | YES | MUL | NULL | |
| release_date | varchar(45) | YES | | NULL | |
| name | varchar(45) | YES | | NULL | |
| format | varchar(45) | YES | | NULL | |
| music_genre_id | int(11) | YES | MUL | NULL | |
| label_id | int(11) | YES | MUL | NULL | |
| avg_rating | float | YES | | NULL | |
+----------------+-------------+------+-----+---------+----------------+
和music_ratings
+-----------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------+------+-----+---------+----------------+
| music_rating_id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | YES | MUL | NULL | |
| album_id | int(11) | YES | MUL | NULL | |
| rating | int(11) | YES | | NULL | |
+-----------------+---------+------+-----+---------+----------------+
每次插入* music_rating *后,我想更新相册表中的平均评分。我有一个触发器,它调用一个过程。问题是,该过程不起作用,由于某种原因,游标不从表中获取数据。 (我分别调用了程序,以确保它不是触发器。表已经有几行,所以不是那样。)
我的程序很简单,看起来像这样
DELIMITER $$
CREATE PROCEDURE avg_album_calc(IN id_album INT)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE rating INT;
DECLARE cur CURSOR FOR SELECT `rating` FROM `music_ratings` WHERE `album_id`=id_album;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
SET @ct=0;
SET @sm=0;
REPEAT
FETCH cur INTO rating;
IF NOT done
THEN
SET @ct = @ct +1;
SET @sm = @sm + rating;
END IF;
UNTIL done END REPEAT;
UPDATE albums SET avg_rating = @sm/@ct WHERE album_id = id_album;
CLOSE cur;
END$$
DELIMITER ;
我在SELECT rating
命令之后用FETCH cur INTO rating;
回显了光标的结果,它显示为null。
答案 0 :(得分:0)
您无需在avg_rating
表格中计算和存储albums
。你可以动态计算 -
SELECT a.album_id, a.name, AVG(mr.rating) FROM albums a
LEFT JOIN music_ratings mr
ON a.album_id = mr.album_id
GROUP BY a.album_id