MYSQL获取民意调查结果表

时间:2019-03-08 04:43:29

标签: mysql

我有2张桌子,一张带有投票答案,一张带有投票:

DESC polls;

Field   Type      Null  Key Default Extra
id      int(11)   NO    PRI NULL    auto_increment
pollId  int(11)   NO    MUL NULL    
answer  varchar(150)    YES NULL    

DESC votes;
Field    Type      Null Key Default Extra
id       int(11)    NO  PRI NULL    auto_increment
pollId   int(11)    NO  MUL NULL    
answerId int(11)    NO  MUL NULL    
userId   int(11)    NO  MUL NULL    

我正在尝试获得所有答案和投票的以下结果:

pollId answerId numberOfVotes
1        1          20
1        2          10
1        3          0

我尝试通过正确的选票方式来回答问题,但这不起作用:

SELECT answers.id, COUNT(votes.answerId) FROM answers JOIN votes ON votes.pollId = answers.pollId GROUP BY votes.pollId;

1 个答案:

答案 0 :(得分:1)

使用左联接

DEMO

SELECT polls.pollId,polls.id,COUNT(userid) as counts
FROM polls left JOIN votes ON votes.pollId = polls.pollId and 
polls.id=votes.answerId
GROUP BY polls.pollId,polls.id order by polls.id

输出:

pollId  id  counts
14      17  0
14      18  2
14      19  0
14      20  0