2017-01-16 54 views
1

我有情況下,用戶,我需要選擇該回答這個問題在SQL 我的表正確看用戶的每一個問題數量一樣讓每一個問題,許多答對

table 1: questionnaire_question 
id - question_text - thecorrectAnswer 

table 2 :questionnaire_answers 
id - user_id - question_id - user_answer - correct 

正確的列有用戶回答值爲0或1的正確與否

回答

0

使用LEFT JOINGROUP BYCOUNT

select 
    q.id, 
    count(distinct a.user_id) cnt -- can be replaced with count(*) 
           -- if a user has only at max one correct answer 
           -- for a given question 
from questionnaire_question q 
left join questionnaire_answers a 
on q.id = a.question_id 
where correct = 1 
group by q.id; 
0

您可以加入表和count一個case表達,檢查正確性:

SELECT q.id, cnt 
FROM questionnaire_question q 
JOIN (SELECT question_id, COUNT(CASE correct WHEN 1 THEN 1 END) AS cnt 
     FROM questionnaire_answers 
     GROUP BY question_id) a ON q.id = a.question_id 
0

使用子查詢,如果問題沒有正確答案,則返回0

試試這個:

SELECT qq.id, 
    COALESCE((SELECT COUNT(*) 
    FROM questionnaire_answers qa 
    WHERE qa.question_id = qq.question_id 
    AND qa.correct = 1), 0) 
FROM questionnaire_question qq 
0
select question_id, count(user_id) 
from questionnaire_answers 
where correct = 1 
group by question_id 

沒有加入因爲您已經通過包含正確的列來非規範化模式。