我有表格问题表,包含以下列和数据
QuestionId QuestionText
1 what is my name
2 xxx
3 yyy
我有ExamQuestionAnswer表,其中包含以下列和数据
ExamId QuestionID Answer
1 1 abc
1 2 def
2 1 abc
2 2 xyz
现在我想显示所有问题和答案,无论是否回答问题。
请帮我查询
提前致谢。
答案 0 :(得分:1)
试试这个:
SELECT A.ExamID ,
Q.QuestionID ,
Q.QuestionText ,
ISNULL(A.Answer, '-') Answer
FROM dbo.Question Q WITH ( NOLOCK )
LEFT JOIN dbo.ExamQuestionAnswer A WITH ( NOLOCK ) ON Q.QuestionId =
A.QuestionId
答案 1 :(得分:0)
为此,您需要在两个表之间使用外连接才能为您工作。
select t1.QuestionId, t1.QuestionText, ISNULL(t2.Answer,'') as Answer
from Question t1
left outer join ExamQuestionAnswer t2
on t1.QuestionId = t2.QuestionId
答案 2 :(得分:0)
尝试加入他们:
SELECT *
FROM QuestionId t1
JOIN ExamQuestionAnswer t2 ON t1.QuestionId = t2.QuestionID
WHERE t2.ExamId = [X];
[X]
<{1}}是Exam ID
答案 3 :(得分:0)
如果给定的问题确实从未得到回答,我会在显示有意义的信息时提供轻微的变化:
SELECT
COALESCE(t2.ExamId, 0) AS ExamId, -- display 0 for non matches
t1.QuestionId,
t1.QuestionText,
COALESCE(t2.Answer, 'Never answered') AS Answer
FROM Question t1
LEFT JOIN ExamQuestionAnswer t2
ON t1.QuestionId = t2.QuestionId;
根据请求,我将ExamId
添加到选择列表中。 ExamId
非匹配问题的值为零。
答案 4 :(得分:0)
SELECT e.ExamId AS 'Exam Id',
q.QuestionId AS 'Question Id',
q.QuestionText AS 'Question Text',
IS NULL(e.Answer, 'No Answer') AS 'Answer'
FROM Question q LEFT JOIN ExamQuestionAnswer e
ON q.QuestionId = e.QuestionId