null - MySQL: AVG when there are no matching rows -


i'm creating website users can rate items (say books), 1 5 stars. have created mysql database , table stores info each rating (itemid, userid, ratingvalue).

each item has dedicated webpage, , i'd put on page info about: (1) number of ratings , (2) average rating. thought best done view. in thinking mysql queries use in view, came to:

select itemid, count(ratingvalue), ifnull(avg(ratingvalue),0) reviews group itemid

problem: if item not yet rated, not appear on query. items appear in query result (view), , if there item no reviews, should appear information there 0 reviews , average rating arbitrary value, let's 0.

from official documentation,

avg() returns null if there no matching rows

and reason tried use ifnull() function. however, doesn't work. example, in database items 1,2,3,4,5, item 5 has no reviews, i'll get:

  itemid  count(rating)   ifnull(avg(ratingvalue),0) 1           4                4.0000 2           2                4.0000 3           2                3.5000 4           3                5.0000 

any ideas on how overcome problem?

you have have table lists of items (without regard whether have reviews) , left join table reviews table. without that, there no way infer reviews table alone items may exist have no reviews.

so like:

select     i.itemid itemid,     count(r.rating) ratingcount,     avg(ratingvalue) averagerating items left join reviews r   on i.itemid = r.itemid group i.itemid 

this should give results like:

itemid  ratingcount   averagerating 1       4             4.0000 2       2             4.0000 3       2             3.5000 4       3             5.0000 5       0             null 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -