1

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

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

一些表的解释:

  1. answer_chk_results- 检查答案表。因此,如果此表上不存在某些答案,则表示未选中
  2. lesson_questions- 课程 <-> 问题关联(按 id)表

当我这样查询数据库时:

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 个问题)我错过了什么?

4

1 回答 1

5

Agroup 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_resultscount(distinct acr.checked)返回选中列的不同值的数量。如果选中的是布尔值,则始终为一或零。

于 2012-09-01T11:15:21.310 回答