I have two tables, one with products
and another with ratings
.
I want to list all products
and if a user has rated the product (then r.by is the userId and r.rating is the rating) then I want to add a userrating
=r.rating else userrating=0 to the SQL response.
It works with only one user, so I don't know what's wrong with it.
$sql = "SELECT DISTINCT p.id, p.rating, CASE WHEN r.by=:USER_ID
THEN r.rating ELSE 0 END AS userrating FROM `products` p
LEFT OUTER JOIN `ratings` r
ON r.productid=p.id
WHERE p.moderated=1
order by p.rating desc";
EDIT:
I need to list all the products, and if a user has rated the product, I need the users rating attached as "userrating"=(the users rating).