0

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).

4

1 回答 1

0

改变:

SELECT DISTINCT p.id, p.rating, CASE WHEN r.by=:USER_ID

至:

SELECT DISTINCT p.id, p.rating, CASE WHEN r.by IS NOT NULL

更简单的是,您可以将 CASE 语句替换为 COALESCE:

SELECT DISTINCT p.id, p.rating, COALESCE(r.rating, 0) AS userrating 
FROM `products` p
...

请注意,如果多个用户对单个产品给出了不同的评分,您将返回多行 - 每个不同的评分值对应一个。

更新

要获得单个用户 id 的评级(作为 传递USER_ID),最简单的方法是过滤外部连接本身:

SELECT DISTINCT p.id, p.rating, COALESCE(r.rating, 0) AS userrating 
FROM `products` p 
LEFT OUTER JOIN `ratings` r
  ON r.productid=p.id AND r.by=:USER_ID
WHERE p.moderated=1
ORDER BY p.rating desc
于 2013-06-11T13:40:31.127 回答