如何使用mysql获得评级系统中的最高平均值?

时间:2016-01-27 05:57:11

标签: mysql sql

我正在我的产品页面中创建一个排序,并使用评级实现排序。 我的问题是我得到了多排相同的产品。

这是我的疑问:

SELECT DISTINCT(p.product_id) AS product_id, p.model AS model, r.rating AS rating FROM jp_product AS p
LEFT JOIN jp_review AS r
ON(p.product_id = r.product_id)
LEFT JOIN jp_user AS u
ON(p.seller_id = u.user_id)
WHERE p.`status` = 1
AND u.`status` = 1
ORDER BY r.rating DESC;

结果如下:

*************************** 1. row ***************************
product_id: 143
     model: Kagoshima Satsuma-age
    rating: 5
*************************** 2. row ***************************
product_id: 145
     model: Filter-in Bottle
    rating: 5
*************************** 3. row ***************************
product_id: 143
     model: Kagoshima Satsuma-age
    rating: 2
*************************** 4. row ***************************
product_id: 145
     model: Filter-in Bottle
    rating: 2
*************************** 5. row ***************************
product_id: 51
     model: 4901362107276
    rating: NULL
*************************** 6. row ***************************
product_id: 69
     model: a3
    rating: NULL

...

如您所见,产品ID 143和145重复。 你能帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

使用MAX(rating)

SELECT p.product_id AS product_id, p.model AS model, MAX(r.rating) AS      
rating
FROM jp_product AS p
LEFT JOIN jp_review AS r
    ON (p.product_id = r.product_id)
LEFT JOIN jp_user AS u
    ON (p.seller_id = u.user_id)
WHERE p.`status` = 1 AND u.`status` = 1
GROUP BY p.product_id, p.model
ORDER BY r.rating DESC;

答案 1 :(得分:1)

您可以尝试以下查询 -

SELECT p.product_id AS product_id, p.model AS model, MAX(r.rating) AS rating 
FROM jp_product AS p
JOIN jp_review AS r ON p.product_id = r.product_id
JOIN jp_user AS u ON p.seller_id = u.user_id
WHERE p.`status` = 1 AND u.`status` = 1
GROUP BY p.product_id;

注意:当您从jp_user过滤数据时,也意味着您只需要匹配的行,因此不需要左连接简单连接。

group by也会使行唯一,因此不需要明确。

此外,如果您想基于product_id进行排序,请在最后按product_id应用订单。