我有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
除了voter
之外,您会注意到这两个输出是相同的。
我缺少的查询是一种确定给定用户(例如voter=acct_id=5
)是否是对任何评论投票的用户的方法。如果没有这个条件,查询会从列表中选择voter
comment_id=5
为voter=1
的第一个SELECT from votes where voter='X'
。
所以我的问题是我认为我需要插入以下子查询:
from
我只是不确定在哪里或如何。将它放在上面votes
和sum()
之间的括号中会消除{{1}}函数,因此我陷入困境。
有什么想法吗?
答案 0 :(得分: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