SQL Query需要显示所有记录

时间:2017-11-23 11:36:43

标签: sql sql-server join

我有表格问题表,包含以下列和数据

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

现在我想显示所有问题和答案,无论是否回答问题。

请帮我查询

提前致谢。

5 个答案:

答案 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

点击此处:SQL LEFT JOIN KeywordISNULL (Transact-SQL)

答案 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;

enter image description here

根据请求,我将ExamId添加到选择列表中。 ExamId非匹配问题的值为零。

Demo

答案 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