我有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=5
爲voter=1
。
所以我的問題是,我想我需要插入下面的子查詢:
SELECT from votes where voter='X'
我只是不知道在哪裏或如何。將它放在上面的from
和votes
之間的括號中可消除sum()
函數,因此我被卡住了。
有什麼想法?
但是,如果在您的示例中,評論已收到來自多個用戶的投票...哪個投票者應該出現在您的輸出中? – eggyal
嗨eggyal,我希望查詢不僅選擇所有評論和他們的總票數,而且要選擇acct_id = X是否已對評論投票。 –
那不是'did_i_vote'列的功能嗎?哪個選民應出現在「選民」專欄中? – eggyal