MySQL COUNT意外结果

时间:2012-09-01 11:11:03

标签: mysql sql database

我的数据库结构如下所示:

https://docs.google.com/open?id=0B9ExyO6ktYcOenZ1WlBwdlY2R3c

一些表的解释:

  1. answer_chk_results - 已检查答案表。因此,如果此表中不存在某些答案,则表示未经检查
  2. lesson_questions - 课程< - >问题关联(通过id)表
  3. 当我像这样查询数据库时:

    SELECT
        q.id,
        q.content,
        q.type
    FROM
        `questions_and_exercises` q,
        `lesson_questions` lq
    WHERE
        q.id = lq.qid
    AND lq.lid = 1
    

    我收到所有问题清单。但我想要的是每个问题的答案和检查答案。当我使用此查询时:

    SELECT
        q.id,
        q.content,
        q.type,
        COUNT(DISTINCT a.ID) answer_count,
        COUNT(DISTINCT acr.id) checked_count
    FROM
        `questions_and_exercises` q,
        `lesson_questions` lq
    LEFT JOIN answers a ON a.qid = lq.qid,
    LEFT JOIN `answer_chk_results` acr ON acr.aid = a.id
    WHERE
        q.id = lq.qid
    AND lq.lid = 1
    

    结果只有1个问题,错误的答案数。 (我的数据库中有大约9-10个问题)我缺少什么?

1 个答案:

答案 0 :(得分:5)

group by会有所帮助,例如:

select  q.id
,       q.content
,       q.type
,       count(distinct a.id) as answer_count
,       count(acr.checked) as checked_count
from    questions_and_exercises q
join    lesson_questions lq
on      q.id = lq.id
left join
        answers a 
on      a.qid = lq.qid
left join
        answer_chk_results acr 
on      acr.aid = a.id
group by
        q.id
,       q.content
,       q.type

请注意,count(acr.checked)会返回answer_chk_results表中有一行的答案数。并且count(distinct acr.checked)返回已检查列的不同值的数量。如果checked是布尔值,则该值始终为1或0。