按评论数量对产品进行排序

时间:2011-05-09 15:54:23

标签: php mysql sorting

我有一个带

的mysql数据库
  • 表'product'包含列'product_id','name','price'
  • 表'评论'包含列'review_id','product_id','review_content'

我想检索'product_id'= 123的结果,但按评论数量排序。我可以使用COUNT('review_id')找到特定产品的评论数量,但如何按评论数量对结果进行排序?

4 个答案:

答案 0 :(得分:2)

由于您可能在查询中选择COUNT('review_id'),因此您最后只需添加ORDER BY COUNT('review_id') DESC即可。

答案 1 :(得分:1)

尝试使用此功能获取所有产品和评论数量:

SELECT P.*, IFNULL(COUNT(R.product_ID),0) AS NumReviews
FROM Product AS P
LEFT JOIN Review AS R ON R.product_id = p.product_id
ORDER BY  COUNT(R.product_ID) DESC

答案 2 :(得分:1)

要保存两次使用计数: count('review_id') as num_reviews然后order by num_reviews

答案 3 :(得分:1)

如果您想要评价最多的产品......

SELECT P.product_id, 
       IFNULL(COUNT(R.product_ID),0) as "Reviews"
FROM product as P
LEFT JOIN review as R ON P.product_ID = R.product_id
GROUP BY P.product_id
ORDER BY Review DESC;

...否则请使用DESC切换ASC