phpmyadmin

时间:2017-09-12 07:59:45

标签: mysql phpmyadmin

我在问题表中有3个表(用户,问题,答案)我有id_question和问题,在答案表中我有id_questionuser_id并回答。我想运行一个查询,给出每个问题的答案数。

我想要一个列,其中包含已回答的所有问题(不是id_question)和其他3个列(是,否,可能),这些列具有对问题给出答案的次数。问题栏不能有重复的问题(即使用户可以回答相同的问题并给出不同的答案,我想要每个问题的是,否和可能的数量)。我只创建了yes列,在创建其他2

时遇到了麻烦

这是我到目前为止所做的:

SELECT 
    questions.question, COUNT(answers.answer) As Yes
FROM 
    answers 
INNER JOIN 
    questions ON questions.id_question = answers.id_question 
WHERE 
    answer = 'yes' 
GROUP BY 
    question  
ORDER BY 
    questions.id_question  ASC

1 个答案:

答案 0 :(得分:0)

SELECT questions.question,
    SUM(IF(answer='yes', 1, 0)) AS Yes,
    SUM(IF(answer='no', 1, 0)) AS No,
    SUM(IF(answer='maybe', 1, 0)) AS Maybe
FROM answers 
INNER JOIN questions ON questions.id_question=answers.id_question 
GROUP BY question
ORDER BY questions.id_question ASC