【发布时间】:2012-05-11 12:58:02
【问题描述】:
我有 MySQL 查询,我认为它需要一个子查询。我想计算对许多 cmets 中每一个的“赞成”投票总数,并确定给定用户是否已经对每条评论投票:
这是我的桌子:
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)是否是对任何 cmets 投票的人的方法。如果没有该条件,查询将选择列表中的第一个voter,对于comment_id=5,它是voter=1。
所以我的问题是我认为我需要插入以下子查询:
SELECT from votes where voter='X'
我只是不确定在哪里或如何。把它放在上面的from 和votes 之间的括号中消除了sum() 函数,所以我被卡住了。
有什么想法吗?
【问题讨论】:
-
但是,如您的示例所示,如果某条评论收到了来自多个用户的投票……您的输出中应该出现哪个投票者?
-
嗨,eggyal,我希望查询不仅可以选择所有 cmets 及其总票数,还可以选择 acct_id=X 是否对评论进行了投票。
-
这不是
did_i_vote列的作用吗?哪个选民应该出现在voter列中? -
是的,这就是 did_i_vote 列应该要做的事情。 voter="X" 投票是否应该出现在该列中