2012-05-02 41 views
0

我有MySQL查詢,我認爲需要一個子查詢。我想指望每一種的許多意見的「向上」的投票總數,並確定給定用戶是否已經投票每個評論:關於評論投票的mysql子查詢問題

這裏是我的表:

Comments Table: 
    comment_id comment  acct_id  topic_id comment_date 
     5  hello5  2    1   9:00am 
     7  hello7  3    1   10:00am 

    Votes Table: 
    comment_id vote  acct_id  topic_id 
    5   1    1   1 
    7   1    4   1 
    5   1    5   1 

這裏的輸出我得到:

comment_id commenter comment voter sum did_i_vote 
     5   2  hello5  1  2   1 
     7   3  hello7  4  1   1 

下面是所需的輸出:

comment_id commenter comment voter sum did_i_vote 
     5   2  hello5 **5** 2   1 
     7   3  hello7  4  1   1 

這裏是我的曲紅黴素:

SELECT votes.acct_id as voter, comments.comment_id, comment, comments.acct_id as 
commenter, SUM(vote) as sum, vote as did_i_vote 
from votes 
right join comments 
on votes.comment_id=comments.comment_id 
join accounts on comments.acct_id=accounts.acct_id 
where topic_id=1 
group by comments.comment_id order by comment_date desc 

你會發現這2個輸出,除了voter相同。

我的查詢缺失的是確定給定用戶(例如voter=acct_id=5)是否是對任何評論投票的人。沒有這種條件,查詢將在列表中選擇第一個voter,對於comment_id=5voter=1

所以我的問題是,我想我需要插入下面的子查詢:

SELECT from votes where voter='X' 

我只是不知道在哪裏或如何。將它放在上面的fromvotes之間的括號中可消除sum()函數,因此我被卡住了。

有什麼想法?

+0

但是,如果在您的示例中,評論已收到來自多個用戶的投票...哪個投票者應該出現在您的輸出中? – eggyal

+0

嗨eggyal,我希望查詢不僅選擇所有評論和他們的總票數,而且要選擇acct_id = X是否已對評論投票。 –

+0

那不是'did_i_vote'列的功能嗎?哪個選民應出現在「選民」專欄中? – eggyal

回答

1

如果我從上面的評論中正確地理解了你,我認爲你所需要做的就是(外部)再次將votes表加入您的查詢表中,這次僅針對相關帳戶的投票:

SELECT 
    comments.comment_id  AS comment_id, 
    comments.acct_id   AS commenter, 
    comment     AS comment, 
-- votes.acct_id    AS voter,      -- ambiguous 
    SUM(votes.vote)   AS sum, 
    my_votes.vote IS NOT NULL AS did_i_vote 
FROM 
      votes 
    RIGHT JOIN comments ON votes.comment_id=comments.comment_id 
     JOIN accounts ON comments.acct_id=accounts.acct_id -- what purpose ? 
    LEFT JOIN votes AS my_votes ON 
       my_votes.commentid=comments.comment_id 
      AND [email protected]_acct_id 
WHERE topic_id = 1           -- ambiguous 
GROUP BY comments.comment_id 
ORDER BY comment_date DESC 
+0

嗨eggyal,真棒!這完全符合我的需要。你能解釋一下外連接和子查詢的區別嗎?我想我仍然不確定何時使用一個和另一個。 –

+0

@timpeterson:外部連接將兩個表連接在一起,但是如果連接條件中沒有匹配,它將不會從「LEFT」或「RIGHT」表中刪除任何記錄(如指定):這些記錄仍然顯示,但是在連接另一端的表的每一列中都帶有NULL。子查詢是在查詢中使用另一個'SELECT'查詢 - 它不需要連接到其他表,但是如果它像其他連接那樣可以是內部或外部的;例如,您可以在WHERE子句中使用子查詢,而不是將它們與查詢中的表連接起來。這有幫助嗎? – eggyal

+0

真棒,這有助於很多! –