2011-11-17 111 views
0

我正在撰寫一個查詢以獲得評級最高的10家企業,每個企業的正面評論數量,每個企業的負面評論數量和最新評論爲每個這些業務。選擇總評論(pos&neg)+最新評論爲每個

SELECT comment.bis_id, Sum(Case When comment.rating <= 2 Then 1 Else 0 End) As NegVotes 
, Sum(Case When comment.rating >= 4 Then 1 Else 0 End) As PosVotes, bis.bis_name 
FROM bis, comment 
WHERE comment.bis_id = bis.bis_id 
GROUP BY bis_id 
ORDER BY PosVotes DESC 
LIMIT 0, 10"; 

以上得到正面評論和負面評論,但我似乎無法找出如何獲得最新評論爲好。

回答

0
SELECT 
    c.bis_id 
    , Sum(Case When c.rating <= 2 Then 1 Else 0 End) As NegVotes 
    , Sum(Case When c.rating >= 4 Then 1 Else 0 End) As PosVotes 
    , b.bis_name 
    , cc.last_comment 
FROM bis b 
INNER JOIN comment c on (c.bis_id = b.bis_id) 
INNER JOIN (SELECT c2.bis_id, c2.comment_text as last_comment 
      FROM comment c2 
      GROUP BY c2.bis_id 
      HAVING c2.comment_date = MAX(c2.comment_date)) cc 
     ON (cc.bis_id = b.bis_id)   
GROUP BY b.bis_id 
ORDER BY PosVotes DESC 
LIMIT 10 OFFSET 0 
+0

非常感謝,謝謝。我認爲它應該是GROUP BY c2.bis_id。我還必須將第9行更改爲: INNER JOIN(SELECT c2.bis_id,c2.comment_date,c2.comment_text as last_comment 但之後,它似乎不像預期的那樣工作 - 它將大多數企業從查詢中排除。當我將HAVING子句更改爲c2.comment_date = MIN(c2.comment_date)時似乎正常工作 任何想法? – Neil