我有以下表格:问题,答案,User_Answers
我试图获得一个查询,我可以打印出问题,答案和用户选择的答案。
到目前为止,Iv设法用用户答案打印出问题,但没有任何顺序。
包含样本数据的表:
**Question Table**
id Test_ID QText
--------------------------------------------
1 1 What colour is the sky?
**Answer Table**
id Question_ID AText
-------------------------------
1 1 Green
2 1 Blue
3 1 Red
4 1 Yellow
**User_Answers Table**
id User_ID Question_ID Answer_ID
---------------------------------------------------
1 1 1 2
**Correct_Answers Table**
id Question_ID Answer_ID
---------------------------------------------------
1 1 1
Expected Outcome :
Question xxxxxxx
Answer Your Answer Correct Answer
------------------------------------------
1 x
2 x
3
4
答案 0 :(得分:2)
SELECT
q.QText, q.id AS QId, ua.id, qa.AText,
case when qa.ID = ua.Answer_ID then 'x' else NULL end as IsUserAnswer
FROM user_answers ua
INNER JOIN question q ON q.ID = ua.Question_ID
INNER JOIN answer qa ON qa.Question_ID = q.ID
WHERE ua.User_ID=1
ORDER BY QId, qa.ID
您错过了questions
answers
到question_id
的加入