你如何订购两张桌子?

时间:2011-12-21 21:54:32

标签: php mysql sql

我就是你在MySQL上称之为'noob'的东西。我可以插入/编辑/选择东西,但比这更先进的东西让我感到困惑。我的数据库中有两个表:

表'评论'

id      int(11)
review  varchar(2500)
game    int(11)
user    int(11)
title   varchar(200)`

表'review_rating'

user    int(11)
review  int(11)     // Corresponds to `reviews.id`
like    tinyint(1)

以下是我的问题:是否可以在ORDER BY表格上使用reviews来按照“like”= 1(其中“review”= id)的review_ratings总数对结果进行排序'评论'表)除以review_ratings的总数(其中'review'='评论'表的ID)。

示例:

SELECT * 
FROM `reviews` 
WHERE `game` = ? 
ORDER BY (total number of review_ratings where review = reviews.id and like = 1 / 
         total number of review_ratings where review = reviews.id) 
LIMIT 0, 10

3 个答案:

答案 0 :(得分:2)

我认为将它放在SELECT子句中更清楚:

SELECT reviews.*,
       ( SELECT SUM(like) / COUNT(1)
           FROM review_ratings
          WHERE review = reviews.id
       ) like_ratio
  FROM reviews
 WHERE game = ?
 ORDER
    BY like_ratio DESC
 LIMIT 10
;

注意:

  • 未经测试;我现在远离MySQL盒子。
  • 我认为如果你愿意,你可以将子查询移动到ORDER BY子句,但无论如何它都是一个有用的东西。
  • 如果给定的评论没有评分,我不确定上述情况会怎样。您可能需要使用CASE表达式来处理这种情况。

答案 1 :(得分:2)

SELECT  t.review,
        Score = CASE WHEN TotalReviews<> 0 THEN LikedReviews/TotalReviews ELSE NULL END
  FROM  (
              SELECT    *,
                    (SELECT COUNT(*) FROM review_rating WHERE review = r.review) AS TotalReviews ,
                    (SELECT COUNT(*) FROM review_rating WHERE review = r.review AND like = 1) AS LikedReviews,
              FROM  review r        
             WHERE  game = ?
         )t
ORDER BY t.review, Score

答案 2 :(得分:0)

这样的事情可以通过每次审核的总评论来排序:

select( count(review.id) as 'total' from reviews join review_rating on review.id = review_rating.review group by review.id) order by total

数学并不完全是你所拥有的,但希望你能得到它