一起查询两个表,只显示一个记录

时间:2012-10-16 15:28:36

标签: php mysql sql

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

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 个答案:

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

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

{{1}}

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

答案 3 :(得分:0)

您缺少的是“GROUP BY”。在获取总和时使用GROUP BY PollID