2011-02-28 43 views
0

我需要實現一些這樣的事AVG和ISNULL在MySQL

SELECT ISNULL(AVG(rating),0) FROM videorating vr WHERE vr.VideoId=11229; 

如果平均是空/空那麼我應該得到0的評級。

我試圖優化這個查詢

SELECT CASE ISNULL(AVG(rating)) WHEN 0 THEN AVG(rating) ELSE 0 END AS rating FROM videorating WHERE videoID=11229; 
+0

問題是什麼?你有錯誤嗎?我認爲你正在尋找的函數是'IFNULL(exp1,exp2)'。函數ISNULL(exp)只有一個表達式,並返回true或false。 – Galz 2011-03-03 19:59:14

回答

0

個人而言,我會使用觸發器來保持的平均等級,因爲它會爲你的數據庫的大小增長更有效率 - 那麼你可以簡單地做:

select rating from video where video_id = 1; 

完整的腳本如下:

drop table if exists video; 
create table video 
(
video_id int unsigned not null auto_increment primary key, 
title 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 video_vote; 
create table video_vote 
(
video_id int unsigned not null, 
user_id int unsigned not null, 
score tinyint unsigned not null default 0, -- 0 to 5 
primary key (video_id, user_id) 
) 
engine=innodb; 

delimiter # 

create trigger video_vote_after_ins_trig after insert on video_vote 
for each row 
begin 
update video set 
    num_votes = num_votes + 1, 
    total_score = total_score + new.score, 
    rating = total_score/num_votes 
where 
    video_id = new.video_id; 
end# 

delimiter ; 

insert into video (title) values ('video 1'),('video 2'), ('video 3'); 

insert into video_vote (video_id, user_id, score) values 
(1,1,5),(1,2,4),(1,3,3),(1,4,2),(1,5,1), 
(2,1,2),(2,2,1),(2,3,4), 
(3,1,4),(3,5,2); 

select rating from video where video_id = 1;