带计数的SQL多重连接

时间:2014-10-08 15:00:07

标签: sql join count

我有三张桌子:

FORM(id)

QUESTION(id, form_id, text)  --> X questions for a form

ANSWER(id, question_id, answer_number, text) --> X answers for a question

我还有一个表格,供用户给出答案:

USERS_ANSWERS(id, question_id, answer_number)

对于每个问题,我希望得到答案给出的COUNT,例如:

question_id,answer_number,COUNT(用户回答此问题)

如果没有答案,则count = 0。

你能帮帮我吗?这需要几个小时,我什么都没有。 :(

PS:是的,我知道,为什么我在USERS_ANSWERS中没有使用answer_id?我不知道,这不是我的数据库...

3 个答案:

答案 0 :(得分:2)

简单的JOIN应该这样做;

SELECT q.id question_id, a.answer_number, COUNT(ua.id) answer_count
FROM question q
JOIN answer a 
  ON q.id = a.question_id
LEFT JOIN users_answers ua 
  ON q.id = ua.question_id AND a.answer_number = ua.answer_number
GROUP BY q.id, a.answer_number
ORDER BY q.id, a.answer_number

第一个JOIN将所有问题与他们的答案相结合,以获得所有有效组合。以下LEFT JOIN计算所有组合的所有答案,允许零计数。

An SQLfiddle to test with

答案 1 :(得分:0)

您只需要分组(question_id,answer_number)然后计算

select 
question_id, answer_number, count(answer_number) as count
from user_answers 
group by question_id, answer_number
order by question_id, answer_number

答案 2 :(得分:0)

对于其他两个表中的每个问题和答案记录,您需要sub query来从USERS_ANSWERS表中获取计数。

以下是这样做的一个例子,即使没有答案也会返回所有问题:

select qst.id                       as 'question_id',
       isnull(ans.answer_number, 0) as 'answer_number',  -- isnull here because not all questions might have answers
       isnull((select count(1)
                 from USERS_ANSWERS usa
                where usa.question_id   = qst.id
                  and usa.answer_number = ans.answer_number), 0) as 'total user answers'
  from QUESTION qst
         left outer join -- left outer join here because not all questions might have answers
       ANSWER   ans on ans.question_id = qst.id