计算多个连接

时间:2011-01-26 19:40:19

标签: mysql join

我有3个表设置(项目,评论,评级)。我想计算每个项目的评分总数和评论总数,然后将它们合并为交互总数,然后根据交互输出最重要的项目。

我正在努力解决这个问题。

SELECT item.id, count(reviews.review_id) AS total_reviews, count(ratings.rating_id) AS total_ratings, total_reviews+total_ratings AS total_interactions FROM items LEFT OUTER JOIN reviews ON reviews.item_id=item.id LEFT OUTER JOIN ratings ON rating.item_id=item.id GROUP BY item.id ORDER BY total_interactions DESC LIMIT 0,1

2 个答案:

答案 0 :(得分:2)

SELECT  *, total_reviews + total_ratings AS total_interactions
FROM    (
        SELECT  id,
                (
                SELECT  COUNT(*)
                FROM    reviews
                WHERE   item_id = i.id
                ) AS total_reviews,
                (
                SELECT  COUNT(*)
                FROM    ratings
                WHERE   item_id = i.id
                ) AS total_ratings
        FROM    items i
        ) q
ORDER BY
        total_interactions DESC
LIMIT 1

答案 1 :(得分:0)

我会尝试修复原始查询,而不是编写另一个查询:

SELECT
    item.id,
    count(distinct reviews.review_id) AS total_reviews,
    count(distinct ratings.rating_id) AS total_ratings,
    count(distinct reviews.review_id) + count(distinct ratings.rating_id) AS total_interactions
FROM
    items
    LEFT OUTER JOIN reviews ON
        reviews.item_id = item.id
    LEFT OUTER JOIN ratings ON
        rating.item_id = item.id
GROUP BY
    item.id
ORDER BY
    total_interactions DESC
LIMIT 0, 1

这里的关键是COUNT(DISTINCT field)。顺便说一句,可能你只需要它来获得total_ratings值 - 只需尝试一下,看看你会得到什么。