我有四十个问题的申请。我在tbAueswer中持有问题及其相应的答案以及用户在tbResult中选择的答案。
这是表结构:
tbQuestion: tbAnswer: tbResult:
QuestionID AnswerID ResultID
QuestionText QuestionID QuestionID
AnswerText AnswerID
UserID
我想选择所有问题,但是如果tbResult中有一行,则表明是否已经回答了问题。它与以下查询的内容类似,但它只选择我已回答的问题。我想使用AS Answered作为是否已经回答的指标。如果没有回答,则为空白,如果已经回答,则为AnswerID。
SELECT tbQuestion.QuestionID, QuestionText, tbAnswer.AnswerID, AnswerText, tbResult.AnseredID AS Answered
FROM tbQuestion
JOIN tbAnswer ON tbQuestion.QuestionID = tbAnswer.QuestionID
LEFT OUTER JOIN tbResult ON tbQuestion.QuestionID = tbResult.QuestionID
WHERE tbResult.UserID = 1234567
此外,还有39个无线电输入答案(每个问题一个答案)和1个带复选框的问题,用户可以为一个问题找到多个答案,因此我们必须知道他们给出的每个答案的答案ID。 / p>
答案 0 :(得分:0)
尝试左外联接tbAnswer
SELECT tbQuestion.QuestionID ,
QuestionText ,
tbAnswer.AnswerID ,
AnswerText ,
tbResult.AnseredID AS Answered
FROM tbQuestion
LEFT OUTER JOIN tbAnswer
ON tbQuestion.QuestionID = tbAnswer.QuestionID
LEFT OUTER JOIN tbResult
ON tbQuestion.QuestionID = tbResult.QuestionID
WHERE tbResult.UserID = 1234567
答案 1 :(得分:0)
将WHERE子句中的条件移动到外连接的ON子句:
select q.questionid,
q.questiontext,
a.answerid,
a.answertext,
r.anseredid as answered
from tbquestion q
join tbanswer a
on q.questionid = a.questionid
left join tbresult r
on q.questionid = r.questionid
and r.userid = 1234567 -- moved to on clause
现在,您的查询仅显示用户实际回答的问题,因为指定用户的条件位于WHERE子句中。如果用户永远不会填写给定问题的答案,他们就不会对tbresult(对于给定的问题)有一行,所以该行将为空。为了允许空值,可以将这些条件放在外连接的on子句中。
答案 2 :(得分:0)
您可以使用:
SELECT tbQuestion.QuestionID, QuestionText, tbAnswer.AnswerID, AnswerText,
case when
tbResult.ResultId is null
then convert(bit, 0)
else convert(bit, 1)
END AS Answered
FROM tbQuestion
JOIN tbAnswer ON tbQuestion.QuestionID = tbAnswer.QuestionID
LEFT OUTER JOIN tbResult ON tbQuestion.QuestionID = tbResult.QuestionID
and tbAnswer.AnswerId = tbResult.AnswerId
and tbResult.UserID = 1234567
获得您问题的大部分答案。 如果您有多个结果(供您多选),您希望如何显示该结果,因为它将是多个resultIds到一个问题?