2011-01-26 93 views
0

我有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
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 
+0

乾杯,我完全沒有! – ATLChris 2011-01-26 20:03:21

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價值 - 只是嘗試一下,看看你會得到什麼。