2011-05-09 82 views
1

我有排序貨品的評語

  • 表「產品」包含列「的product_id」,「名」,「價格」 MySQL數據庫的數量
  • 表「審覈」包含列「REVIEW_ID」 ,'product_id','review_content'

我想檢索'product_id'= 123的結果,但按照評論的數量排序。我可以使用COUNT('review_id')查找特定產品的評論數量,但是如何根據評論數量對結果進行排序?

回答

2

由於您大概在查詢中選擇了COUNT('review_id'),您可以在最後簡單地添加ORDER BY COUNT('review_id') DESC

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 
1

要保存做計數兩次使用: count('review_id') as num_reviews然後order by num_reviews

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; 

...否則切換DESCASC