我有3张表如下
表A - 用户回答
user id | question id | answer option id |
1 | 1 | 2 |
1 | 2 | 1 |
表B - 问题
question id | question text |
1 | Question 1 |
2 | Question 2 |
表C - 答案
answer id | question id | answer option id |answer text |
1 | 1 | 1 |Question 1 answer 1 |
2 | 1 | 2 |Question 1 answer 2 |
2 | 2 | 1 |Question 2 answer 1 |
3 | 2 | 2 |Question 2 answer 2 |
我想找出哪个用户给出了哪个答案 结果应如下所示
1 | Question 1 | Question 1 answer 2 |
1 | Question 2 | Question 2 answer 1 |
我试过了
SELECT * FROM A
LEFT JOIN B ON A.question_id = B.question_id
LEFT JOIN C ON A.answer_option_id = C.answer_option_id
这里有人可以帮助我吗?
答案 0 :(得分:2)
您缺少确保最后一次加入能够获得正确问题的答案。
试试这个:
SELECT * FROM A
LEFT JOIN B ON A.question_id = B.question_id
LEFT JOIN C ON A.answer_option_id = C.answer_option_id AND A.question_id = C.question_id
答案 1 :(得分:0)
你需要通过questionid添加group,否则它将在answer表中为每个返回4行。
Warning message: running command ... had status 127
输出:
select a.userid, b.Qtext, c.Atext from answered a
join quest b on a.qid=b.qid
left join answer c on a.optid=c.optid and a.qid=b.qid group by a.qid;