多次连接表上的LINQ问题

时间:2011-09-12 13:05:41

标签: sql join

我继承了一个架构,我需要让一些sql工作。它是显示产品变化,如跳线的颜色和尺寸变体。该架构有1个产品表:

表tbl_Product

[ProductID] [int],
[Quantity] [int],
[Title] [nvarchar](500),
[Description] [varchar](max),
[Price] [money]  

等...

另一个表作为变体的链接表

表tbl_ProductVariation

[ProductVariationID] [int],
[ProductID] [int] ,
[VariationID] [int]  

和变体表

表tbl_Variation

[VariationID] [int],
[VariationTypeID] [int] NOT NULL,
[USTitle] [nvarchar](150) NULL,
[UKTitle] [nvarchar](150) NULL

所以变化值可以包含颜色或大小,具体取决于variationtypeid

那么为什么这个查询会失败?

SELECT [t4].[ProductVariationID], [t5].[UKTitle] AS [Size], 
       [t6].[UKTitle] AS [Colour], [t0].[Title]
FROM [dbo].[tbl_Product] AS [t0]
INNER JOIN [dbo].[tbl_ProductCategory] AS [t1] 
    ON [t0].[ProductID] = [t1].[ProductID]
INNER JOIN [dbo].[vw_ProductImage] AS [t2] 
    ON [t0].[ProductID] = [t2].[ProductID]
INNER JOIN [dbo].[tbl_Brand] AS [t3] 
    ON [t0].[BrandID] = [t3].[BrandID]
INNER JOIN [dbo].[tbl_ProductVariation] AS [t4] 
    ON [t0].[ProductID] = [t4].[ProductID]
LEFT OUTER JOIN [dbo].[tbl_Variation] AS [t5] 
    ON [t5].[VariationID] = [t4].[VariationID]
LEFT OUTER  JOIN [dbo].[tbl_Variation] AS [t6] 
    ON  [t6].[VariationID] = [t4].[VariationID] 
INNER JOIN [dbo].[tbl_Category] AS [t7] 
    ON [t1].[CategoryID] = [t7].[CategoryID]
WHERE ([t5].[VariationTypeID] IN(2))
AND ([t6].[VariationTypeID] IN(1))

1 个答案:

答案 0 :(得分:2)

如果失败,则表示您的left outer join似乎不起作用,您可以尝试使用此查询。

SELECT [t4].[ProductVariationID],
       [t5].[UKTitle] AS [Size],
       [t6].[UKTitle] AS [Colour],
       [t0].[Title]
FROM   [dbo].[tbl_Product] AS [t0]
       INNER JOIN [dbo].[tbl_ProductVariation] AS [t4]
         ON [t0].[ProductID] = [t4].[ProductID]
       LEFT OUTER JOIN [dbo].[tbl_Variation] AS [t5]
         ON [t5].[VariationID] = [t4].[VariationID] AND
            [t5].VariationTypeID IN(2)
       LEFT OUTER JOIN [dbo].[tbl_Variation] AS [t6]
         ON [t6].[VariationID] = [t4].[VariationID] AND
            [t6].[VariationTypeID] IN(1)

我将VariationTypeID上的检查移到了join子句中。将它们放在where子句中使得外连接的行为类似于内连接。