为什么不同的结果以两种不同的方式编写查询

时间:2013-09-25 01:02:14

标签: sql sql-server-2008-r2

我试图理解为什么以下两个SQL语句给出不同的结果。第一个按预期工作,第二个没有记录。

 Select * from Jet.LayoutListItemEntity_Default itemDefault
 Join  Jet.LayoutListEntity  b
 on itemDefault.UiKey = b.UiKey
 Left join (Select * from Jet.LayoutListItemEntity where DomainId =2) item
 on itemDefault.BindingPath = item.BindingPath
 where item.DomainId is null
 and b.DomainId = 2


 Select * from Jet.LayoutListItemEntity_Default itemDefault
 Join  Jet.LayoutListEntity  b
 on itemDefault.UiKey = b.UiKey
 Left join Jet.LayoutListItemEntity  item
 on itemDefault.BindingPath = item.BindingPath
 where item.DomainId is null
 and item.DomainId = 2
 and b.DomainId = 2

主要区别在于,将item.DomainId = 2放在最后,而不是放在自己的选择中。在我看来,他们会产生相同的结果。

格雷格

2 个答案:

答案 0 :(得分:4)

这些条件相互排斥:

where item.DomainId is null
 and item.DomainId = 2

item.DomainID不能同时为NULL2

您可以将标准移至JOIN条件的标准:

Select * from Jet.LayoutListItemEntity_Default itemDefault
 Join  Jet.LayoutListEntity  b
 on itemDefault.UiKey = b.UiKey
 Left join Jet.LayoutListItemEntity  item
 on itemDefault.BindingPath = item.BindingPath
    and item.DomainId = 2
 where item.DomainId is null
 and b.DomainId = 2

答案 1 :(得分:1)

您的WHERE条件在第二个查询中搞砸了 - 要使这些语句相同,请将and item_DomainId = 2移至JOIN

 Select * from Jet.LayoutListItemEntity_Default itemDefault
     Join  Jet.LayoutListEntity  b
         on itemDefault.UiKey = b.UiKey
     Left join Jet.LayoutListItemEntity  item
         on itemDefault.BindingPath = item.BindingPath and item.DomainId = 2
 where item.DomainId is null
     and b.DomainId = 2