2014-04-02 67 views
-1

我越来越难以理解的区别以下两个查询JOIN和WHERE两个相同的查询

select QuestionSetQuestionAnswer.* 
from QuestionSetQuestionAnswer 
inner join QuestionAnswer 
    on QuestionAnswer.ID = QuestionSetQuestionAnswer.SelectedAnswerID 
     and QuestionAnswer.IsCorrect = 'true' 
where QuestionSetQuestionAnswer.QuestionID = (
       select QuestionID 
       from QuestionSetQuestion 
       where SetID = '45e20157-0030-c58b-55c4-08d11c725bd7' 
              ) 
select QuestionSetQuestionAnswer.* 
from QuestionSetQuestionAnswer 
inner join QuestionSetQuestion 
    on QuestionSetQuestion.QuestionID = QuestionSetQuestionAnswer.QuestionID 
     and QuestionSetQuestion.SetID = '45e20157-0030-c58b-55c4-08d11c725bd7' 
inner join QuestionAnswer 
    on QuestionAnswer.ID = QuestionSetQuestionAnswer.SelectedAnswerID 
     and QuestionAnswer.IsCorrect = 'true' 

两者有什么疑问的区别?他们是一样的吗?

回答

0

第一个查询在QuestionSetQuestion中查找集合ID,并期望找到零个或一个记录匹配。 - 如果它找到一条记录,它会显示与找到的问题ID相匹配的所有QuestionSetQuestionAnswer,并乘以正确答案的数量(假定为0或1我猜)。 - 如果找不到记录,则不显示记录。 - 如果它发现多于一条记录而不是发生运行时错误。所以设置ID对于表格应该是唯一的。 (这看起来有点可疑)。

第二个也是一样的,除了在集合ID上有多个匹配的情况。 - 如果它找到一个或多个记录,它会显示与找到的问题ID相匹配的所有QuestionSetQuestionAnswer,并乘以正确答案的数目(我猜测上面应该是零或一个),再乘以找到的QuestionSetQuestion的数量在第一个查询中被假定为零或一个)。 - 如果找不到记录,则不显示记录。

因此,如果我们总是找到给定集ID的一个或零个记录,那么两个语句都会执行相同的操作。我的观点都不是很好,因为只有一张桌子的纪录应该显示出来,所以为什么要加入其他桌子呢?我想这是什么意思:

select * 
from QuestionSetQuestionAnswer 
where QuestionID = -- or IN if multiple matches are possible 
(
    select QuestionID 
    from QuestionSetQuestion 
    where SetID = '45e20157-0030-c58b-55c4-08d11c725bd7' 
) 
and exists 
(
    select * 
    from QuestionAnswer 
    where ID = QuestionSetQuestionAnswer.SelectedAnswerID and IsCorrect = 'true' 
); 
+0

非常感谢你:) –