这是一个select语句,用于计算数据库中歌曲的平均评分
SELECT *, (tab.rating_sum/tab.rating_count) as rating_average FROM
(SELECT song_id, COUNT(rating) rating_count, SUM(rating) rating_sum FROM ratings
GROUP BY song_id) tab
INNER JOIN SONGS WHERE SONGS.id = tab.song_id
当在RATINGS中插入新评级时,我需要将RATINGS表中的rating_average列插入表SONGS。我还需要确保它进入正确的song_id列。如何使用触发器执行此操作?我一直在撕开我的头发。
这是我能想到的最好的,但我不知道我在使用触发器做什么:
CREATE TRIGGER rating_trig ON ratings FOR INSERT AS
BEGIN
UPDATE SONGS SET
rating = SELECT (tab.rating_sum/tab.rating_count) as rating_average FROM
(SELECT song_id, COUNT(rating) rating_count, SUM(rating) rating_sum FROM ratings
GROUP BY song_id) tab
INNER JOIN SONGS WHERE SONGS.id = tab.song_id
END
表格布局:
评分| song_id,评分,用户名 歌曲| id,rating,song_name
答案 0 :(得分:3)
假设像这样的表结构:
use test;
create table song(
song_id integer,
rating_avg double,
rating_sum integer,
rating_count integer);
create table rating(
song_id integer,
user_id integer,
rating integer);
定义以下触发器:
delimiter $$
create trigger bi_song before insert on test.song
for each row
begin
set NEW.rating_sum = 0;
set NEW.rating_count = 0;
set NEW.rating_avg = NULL;
end
$$
create trigger ai_rating after insert on test.rating
for each row
begin
update song set
rating_sum = rating_sum + NEW.rating,
rating_count = rating_count + 1,
rating_avg = rating_sum / rating_count
where song_id = NEW.song_id;
end
$$
delimiter ;
它应该像这样工作:
mysql> insert into song(song_id) values (1);
Query OK, 1 row affected (0.06 sec)
mysql> select * from song;
+---------+------------+------------+--------------+
| song_id | rating_avg | rating_sum | rating_count |
+---------+------------+------------+--------------+
| 1 | NULL | 0 | 0 |
+---------+------------+------------+--------------+
1 row in set (0.00 sec)
mysql> insert into rating(song_id, user_id, rating) values (1, 1000, 5);
Query OK, 1 row affected (0.05 sec)
mysql> select * from song;
+---------+------------+------------+--------------+
| song_id | rating_avg | rating_sum | rating_count |
+---------+------------+------------+--------------+
| 1 | 5 | 5 | 1 |
+---------+------------+------------+--------------+
1 row in set (0.00 sec)
mysql> insert into rating(song_id, user_id, rating) values (1, 1001, 7);
Query OK, 1 row affected (0.05 sec)
mysql> select * from song;
+---------+------------+------------+--------------+
| song_id | rating_avg | rating_sum | rating_count |
+---------+------------+------------+--------------+
| 1 | 6 | 12 | 2 |
+---------+------------+------------+--------------+
1 row in set (0.00 sec)
这是非常简化的,只是为了说明如何使用触发器。 在实际应用程序中,您将拥有更多列,索引等。