你爲什麼不這樣做,它使用觸發器來維持收視率,所有您需要滿足以下條件要做的是一個非常簡單的查詢來獲得你想要的結果:
隨着表的增長,此方法將更具性能。
希望它可以幫助
例子查詢
select * from food order by rating desc;
+---------+--------+-----------+-------------+--------+
| food_id | name | num_votes | total_score | rating |
+---------+--------+-----------+-------------+--------+
| 1 | food 1 | 6 | 19 | 3.17 |
| 3 | food 3 | 2 | 6 | 3.00 |
| 2 | food 2 | 3 | 7 | 2.33 |
+---------+--------+-----------+-------------+--------+
3 rows in set (0.00 sec)
完整劇本
drop table if exists food;
create table food
(
food_id int unsigned not null auto_increment primary key,
name varchar(255) not null,
num_votes int unsigned not null default 0,
total_score int unsigned not null default 0,
rating decimal(8,2) not null default 0
)
engine = innodb;
drop table if exists food_vote;
create table food_vote
(
food_id int unsigned not null,
user_id int unsigned not null,
score tinyint unsigned not null default 0,
primary key (food_id, user_id)
)
engine=innodb;
delimiter #
create trigger food_vote_after_ins_trig after insert on food_vote
for each row
begin
update food set
num_votes = num_votes + 1,
total_score = total_score + new.score,
rating = total_score/num_votes
where
food_id = new.food_id;
end#
delimiter ;
insert into food (name) values ('food 1'),('food 2'), ('food 3');
insert into food_vote (food_id, user_id, score) values
(1,1,5),(1,2,4),(1,3,3),(1,4,2),(1,5,1),(1,6,4),
(2,1,2),(2,2,1),(2,3,4),
(3,1,4),(3,5,2);
感謝隊友,我用你的代碼和它的工作就像一個魅力!豐富 – Rich 2011-03-15 13:00:32