0

我有我认为需要子查询的 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.

我的查询缺少的是一种确定给定用户(例如 with voter=acct_id=5)是否是对任何评论进行投票的人的方法。如果没有该条件,查询将选择voter列表中的第一个 for comment_id=5is voter=1

所以我的问题是我认为我需要插入以下子查询:

SELECT from votes where voter='X'

我只是不确定在哪里或如何。把它放在上面fromvotes上面之间的括号中会消除这个sum()功能,所以我被卡住了。

有什么想法吗?

4

1 回答 1

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 my_votes.acct_id=@my_acct_id
WHERE topic_id = 1                                            -- ambiguous
GROUP BY comments.comment_id
ORDER BY comment_date DESC
于 2012-05-02T12:09:10.127 回答