【问题标题】:MySQL - Count questionnaire answers.MySQL - 计算问卷答案。
【发布时间】:2014-06-06 12:44:54
【问题描述】:

背景资料

我的表结构如下:

Participants - id, email, organisation_type_id, job_role_id
Answers - id, participant_id, question_id, answer
Questions - id, question, question_category

还有另外两个表,组织类型和工作角色,它们只有一个 id 和一个名称,在上面的表中引用。

这些表格包含有人填写问卷时的数据(每个问题都有一个是或否的答案)。每个问题也属于两个类别之一(由 question_category 字段表示)。

当有人完成问卷时,它会在Participants 表中创建一条记录,并为每个问题在answers 表中创建一条记录。

问题

我想根据特定的组织类型(保存在participants 表中)计算每个问题的肯定答案和否定答案。

例如,如果我想知道属于组织类型 x 的有多少人投了赞成票,有多少人投了反对票,我想要这样的查询:

Count all answers to each question, where the participant has a organisation_type_id of x, group by answer

为了使它更加混乱,我还希望包含该行,即使该特定问题还没有答案。例如,我可能有问题 id x 的答案,但没有来自一个属于 organization_type_id y 的参与者的答案。我希望问题作为一行返回,但在“答案计数”列中为 0。

我的表结构是这里的问题还是只是一个非常令人困惑的查询?到目前为止,我正在使用以下查询,然后使用 PHP 循环遍历结果以检查它是否是我想要的组织或工作角色的一部分,但理想情况下我想在 MySQL 中完成所有操作。

SELECT * FROM `questions`
JOIN `answers` ON `answers`.`question_id` = `questions`.`id`
JOIN `participants` ON `participants`.`id` = `answers`.`participant_id`

提前致谢!

【问题讨论】:

    标签: php mysql sql database


    【解决方案1】:

    试试这个,

    SELECT questions.id
      ,questions.question 
      ,count(answers.id) as totalAns
      ,Sum(Case When participants.id is not null Then 1 Else 0 End) as WithPart
      ,Sum(Case When answers.answer = 'Yes' Then 1 Else 0 End) as YesAns
      ,Sum(Case When answers.answer = 'No' Then 1 Else 0 End) as NoAns
    FROM questions
    left JOIN answers ON answers.question_id = questions.id
    left JOIN participants ON participants.id = answers.participant_id
                            and participants.organisation_type_id = 'x'
    group by questions.id,questions.question 
    

    【讨论】:

      【解决方案2】:

      如果您想回答问题和没有答案的问题,您必须从问题内连接答案中选择。下面的查询给出了答案是或否的问题:

      select p.id, a.answer
      from Participants p
      inner join Answers a ON p.id = a.participant_id
      where a.answer = 'yes' or a.answer = null
      

      【讨论】:

        【解决方案3】:

        你想要所有的问题。所以从问题中选择。您想要某些参与者给出的问题的所有答案。因此,按照这些标准外部加入答案。要在一条记录中获得两个计数(是和否),将它们相加,而不是计算记录。

        select 
          q.id, 
          sum( case when a.answer = 'yes' then 1 ) as yes, 
          sum( case when a.answer = 'no' then 1 ) as no 
        from questions q
        left outer join answers a on a.question_id = q.question_id and a.participant_id in
        (
          select p.id
          from participants p
          where p.organisation_type_id = 'x'
        )
        group by q.id
        order by q.id;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多