2014-02-10 30 views
0

我有以下幾點看法創建爲什麼左連接在sql server中失敗?

create view vw_AllCatSpInst  
as  
select 
    s1.InstructionID as ItemID, 
    s1.CatID, s1.Description as ItemName, 
    s2.MainPrice, s2.PriceFor  
from SpecialInstruction s1 left join 
    Prices s2 on s1.InstructionID=s2.SourceID 
where s2.PriceFor=4 and s1.IsDeleted=0  

create view vw_SpInstCustomziation 
as  
    select s1.ProductID, 
      s2.SourceID, 
      s1.IsDefaultDisplay, 
      s1.IsDefault, 
      s1.DefaultFreeCount, 
      s1.CustomCategoryID 
    from dbo.ProductCustomizationMaster s1 inner join 
     ProductCustomizationDetail s2  
     on s1.CustomCategoryID=s2.CategoryID  
     and s1.ProductID=s2.ProductID 
     and s1.IsDefaultDisplay=1 and s1.CustomType=3 

當我按以下方式查詢這兩種觀點的失敗條件[email protected]和獲取所有左加入記錄。

select s1.ItemID, s1.CatID, s2.ProductID, s1.ItemName, s1.MainPrice, s2.IsDefaultDisplay, s2.IsDefault as IsLimited 
from vw_AllCatSpInst s1 left join 
    vw_SpInstCustomziation s2 
    on s1.ItemID=s2.SourceID 
    and s1.CatID=s2.CustomCategoryID 
where [email protected] 
and [email protected] 
or s2.productid is null 

請幫我這個。

+1

可能需要在where子句中添加括號 –

+0

最後在每個所有視圖中添加括號的位置.. – NoviceToDotNet

+1

如果您說LEFT JOIN,然後有一個引用外部表的WHERE子句,則您的外部聯接將成爲內部加入。 –

回答

2

當您在where子句中的左連接表上進行篩選時,您的連接有效地變爲內連接。您必須將該過濾器用作連接條件。所以這樣的:

from vw_AllCatSpInst s1 left join vw_SpInstCustomziation s2 
on s1.ItemID=s2.SourceID and s1.CatID=s2.CustomCategoryID 
where [email protected] and [email protected] or s2.productid is null 

應該是:

from vw_AllCatSpInst s1 left join vw_SpInstCustomziation s2 
on s1.ItemID=s2.SourceID and s1.CatID=s2.CustomCategoryID 
and [email protected] or s2.productid is null 
where [email protected] 

其實這也許應該是這樣的:

from vw_AllCatSpInst s1 left join vw_SpInstCustomziation s2 
on s1.ItemID=s2.SourceID and s1.CatID=s2.CustomCategoryID 
and 
(
[email protected] or s2.productid is null 
) 
where [email protected] 
1

你的第一個觀點有此查詢:

select s1.InstructionID as ItemID, 
      s1.CatID, s1.Description as ItemName, 
    s2.MainPrice, s2.PriceFor  
from SpecialInstruction s1 left join 
    Prices s2 
    on s1.InstructionID=s2.SourceID 
where s2.PriceFor=4 and s1.IsDeleted=0 ; 

的地方clause has a condition on s2.PriceFor . This condition does not test of NULL . So, although the左加入works correctly, the non-matching records have NULL values. To fix this, move the condition on the second table into the on`條款:

select s1.InstructionID as ItemID, 
      s1.CatID, s1.Description as ItemName, 
    s2.MainPrice, s2.PriceFor  
from SpecialInstruction s1 left join 
    Prices s2 
    on s1.InstructionID=s2.SourceID and s2.PriceFor=4 
where s1.IsDeleted=0 ; 

不要s1移動狀態進入on條款。