使用SELECT CASE和SUM:MYSQL

时间:2013-07-31 20:50:01

标签: mysql sql case

我无法弄清楚如何对某个项目进行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(Joe的情景),问题是vote=-1。同样,my_vote=0如果我使用MIN函数和vote=1(Bob的场景)。

思想?

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:0)

你可以使用这样的东西

选择'total up votes'作为descr,count(*)作为num 来自投票 其中item_id = 1且vote = 1 联合所有 选择'总票数',计数(*) 来自投票 其中item_id = 1且vote = -1 联合所有 选择'my_vote'作为descr,投票 来自投票 其中item_id = 1,voter_id ='joe'