1

我正在构建一个投票系统,我现在有一个查询,应该选择所有投票并计算每个投票的所有投票(位于单独的表中)。所以我的表看起来像:

Polls:  
ID  
Title  
Body

Votes:  
ID  
PollID  
Vote  (This value is either 0 or 1)

好吧,总票数看起来很有效,问题是它目前只显示一条记录。

目前我的查询如下所示:

SELECT POLLS.ID, 
       POLLS.TITLE, 
       POLLS.BODY, 
       Sum(CASE 
             WHEN VOTES.VOTE = 1 
                  AND VOTES.POLLID = POLLS.ID THEN 1 
             ELSE 0 
           END) AS yay, 
       Sum(CASE 
             WHEN VOTES.VOTE = 0 
                  AND VOTES.POLLID = POLLS.ID THEN 1 
             ELSE 0 
           END) AS nay, 
       FROM     polls, 
       VOTES 
ORDER  BY POLLS.ID 

我也将 PHP 与 Codeigniter 一起使用。

4

4 回答 4

1
SELECT polls.ID,polls.title,polls.body,
  SUM(case when votes.vote = 1 then 1 else 0 end) AS yay,
  SUM(case when votes.vote = 0 then 1 else 0 end) AS nay,
FROM polls 
JOIN votes ON polls.ID = votes.pollID
  GROUP BY poll.ID, polls.title, polls.body
  ORDER BY polls.ID
于 2012-10-16T15:35:33.133 回答
0

您需要表中GROUP BY pollID的值votes

SELECT p.ID, p.title, p.body, v.yay, v.nay
FROM
(
    SELECT PollID,
      SUM(CASE WHEN vote = 1 THEN 1 ELSE 0 END) AS yay,
      SUM(CASE WHEN vote = 0 THEN 1 ELSE 0 END) AS nay,
    FROM votes
    GROUP BY PollID
) v
INNER JOIN Polls p ON v.PollID = p.Id
ORDER BY p.ID
于 2012-10-16T15:33:00.377 回答
0

我会去:

    SELECT polls.ID, polls.title, polls.body,
    SUM(IF(votes.vote = 1, 1, 0)) AS yay, 
    SUM(IF(votes.vote = 0, 1, 0)) AS nay
    FROM polls
    JOIN votes ON (votes.pollID = polls.ID)
    GROUP BY ID, title, body
于 2012-10-16T15:36:52.890 回答
0

你缺少的是“ GROUP BY”。GROUP BY PollID取和时使用。

于 2012-10-16T15:48:00.280 回答