两个相同查询的JOIN和WHERE之间的区别

时间:2014-04-02 11:01:10

标签: sql 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'

两个查询之间有什么区别?它们是一样的吗?

1 个答案:

答案 0 :(得分:0)

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

除了在集合ID上存在多个匹配的情况之外,第二个执行相同的操作。   - 如果它找到一个或多个记录,它会显示所有QuestionSetQuestionAnswer匹配找到的问题ID,乘以正确答案的数量(我上面猜测应该是零或一)乘以找到的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' 
);