我就是你在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
答案 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
;
注意:
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
数学并不完全是你所拥有的,但希望你能得到它