1

我不知道如何对SUM某个项目进行上下投票,同时还返回给定用户是否对该项目进行了投票。

这是我的投票表:

item_id vote voter_id
1        -1     joe
1         1     bob
1         1     tom
3         1     bob

item_id=1是我要显示的数据:

如果Joe正在查看页面:

total up votes: 2
total down votes: 1
my_vote: -1

Bob

total up votes: 2
total down votes: 1
my_vote: 1

这是我的代码:

SELECT MAX(CASE WHEN voter_id = 'joe' and vote=1 THEN 1 
WHEN voter_id = 'joe' and vote='-1' THEN -1
ELSE 0 END)
AS my_vote, item_id, sum(vote=1) yes, sum(vote='-1') no
FROM Votes
WHERE item_id=1

问题是,my_vote=0如果我使用MAX函数和vote=-1(乔的场景)。同样,my_vote=0如果我使用 MIN 函数和vote=1(Bob 的场景)。

想法?

4

4 回答 4

3
SELECT
  item_id,
  MAX(CASE WHEN voter_id = 'Joe' THEN vote ELSE NULL END)   AS my_vote,
  sum(vote= 1)   AS yes_votes,
  sum(vote=-1)   AS no_votes
FROM
  Votes
WHERE
  item_id = 1
GROUP BY
  item_id


或者,可能更灵活...

SELECT
  Votes.item_id,
  MAX(CASE WHEN Users.user_id IS NOT NULL THEN Votes.vote ELSE NULL END)   AS my_vote,
  sum(Votes.vote= 1)   AS yes_votes,
  sum(Votes.vote=-1)   AS no_votes
FROM
  Votes
LEFT JOIN
  Users
    ON  Users.user_id = Votes.voter_id
    AND Users.user_id = 'Joe'
WHERE
  Votes.item_id = 1
GROUP BY
  Votes.item_id
于 2013-07-31T21:01:04.433 回答
1

您可以使用相关子查询来获取用户投票,并假设用户每次只能投票一次item_id

SELECT  SUM(vote = 1) totalUpVotes,
        SUM(vote = -1) totalDownVotes,
        (SELECT MAX(vote) 
        FROM votes b
        WHERE a.item_id = b.item_id AND
                b.voter_id = 'joe') my_vote
FROM    votes a
WHERE   item_id = 1
于 2013-07-31T20:57:09.963 回答
1

我的回答几乎是一样的,但是对于我们这些喜欢存储过程的人来说,我已经清理了一点:

declare p_item_id int;
declare p_voter_id varchar(10);

select 
    sum(vote = 1) as TotalUpVotes
    , sum(vote = -1) as TotalDownVotes
    , sum(vote) as TotalScore
    , sum(case when p_voter_id = voter_id then vote else 0 end) as my_vote
from Votes v
where p_item_id = v.item_id
于 2013-07-31T21:56:22.043 回答
0

你可以使用这样的东西

select 'total up votes' as descr, count(*) as num from Votes where item_id=1 and vote=1 union all select'total down votes', count(*) from Votes where item_id=1 and vote=-1 union全部选择'my_vote'作为描述,从item_id = 1和voter_id ='joe'的投票中投票

于 2013-07-31T21:29:53.573 回答