tags:

views:

38

answers:

1

i have two tables products and reviews
each product has several reviews linked by a foreign-key product_id in the reviews table
additionally each review has a field called rating with a decimal value
i wish to get the names of all products whose average rating is above a certain threshold
something in the lines of

SELECT p.name
FROM products p
INNER JOIN reviews r ON p.id = r.product_id
WHERE avg(r.rating) > 3

MySQL is not letting me use the avg function in the where clause.
How do I do something like this?

+6  A: 

use 'having'

SELECT p.name, avg(r.rating) as average
FROM products p
INNER JOIN reviews r ON p.id = r.product_id
GROUP BY p.name
HAVING avg(r.rating) > 3
Luke Schafer
woops - I missed the 'GROUP BY' - fixed
Luke Schafer
That's why sometime the HAVING clause is referred to as 'the WHERE clause of groups'
Remus Rusanu
That takes a lot longer to say than 'having' :)
Luke Schafer
Yes, but once you learn that moniker you never forget when to use WHERE and when HAVING
Remus Rusanu