complex sql:包含products表中的记录,其中join上的值具有在连接表中设置的isdeleted值

时间:2012-04-13 19:40:03

标签: sql sql-server

我有一个提供移动应用的网络服务。出于各种原因,我通过服务将数据发送到应用程序,其中包含将产品,类别产品和类别连接到产品所在的每个类别的单个记录中的查询:

 SELECT * FROM
    (SELECT ROW_NUMBER() OVER(ORDER BY Products.ItemID, Products.ManufacturerID) AS RowNum,
         Products.ProductID, Products.ItemID, Products.ManufacturerID, Categories.CategoryID, Categories.CategoryName, CategoryProducts.CategoryProductID,  Products.ItemName, Products.Description, Products.Notes, 
                      Products.Dimensions, Products.BasePrice, Products.OrderMinimumQuantity, 
                      ContainerMinimumQuantity = 
                        CASE  COALESCE(Products.ContainerMinQty, 0)
                            WHEN 0 THEN Products.OrderMinimumQuantity
                            ELSE Products.ContainerMinQty
                        END 
                      , Products.OrderMultipleQuantity, Products.OnHandQuantity, 
                      Products.Category, Products.IntroDate, Products.BackOrderDate, Products.UPC, Products.PriceLevel1, Products.PriceLevel2, Products.PriceLevel3, 
                      Products.PriceLevel4, Products.PriceLevel5, Products.PriceLevel6, Products.PriceLevel7, Products.PriceLevel8, Products.PriceLevel9, Products.PieceBox, 
                      Products.Cubes, Products.UnitOfMeasure, Products.UDF1, Products.UDF2, Products.UDF3, Products.UDF4, Products.UDF5, Products.AdditionalImageCount, 
                     PhotoName= LOWER(Products.PhotoName),  Products.Discontinued, Products.ModifiedOn, 
                        CategoryProducts.IsDeleted, Products.PriceLevel10, Products.PriceLevel11, Products.PriceLevel12, Products.PriceLevel13, 
                      Products.PriceLevel14, Products.PriceLevel15, Products.PriceLevel16, Products.PriceLevel17, Products.PriceLevel18, Products.PriceLevel19, Products.PriceLevel20, 
                      Products.Weight, Products.DimensionsMetric, Products.Source, Products.InventoryStatus, Products.CatalogCode, Products.CatalogName, 
                       CategoryProducts.SortOrder
 JOIN
                Categories INNER JOIN
                      CategoryProducts ON Categories.CategoryID = CategoryProducts.CategoryID RIGHT OUTER JOIN
                      Products ON CategoryProducts.ManufacturerID = Products.ManufacturerID AND CategoryProducts.ItemID = Products.ItemID
WHERE     (Products.ManufacturerID = @ManufacturerID)
            AND 
            (Products.ModifiedOn > @tStamp OR  CategoryProducts.ModifiedOn > @tStamp)
) AS Products
    WHERE RowNum >= @StartRow AND RowNum <= @EndRow

这使我的所有产品变得扁平化,包括不属于任何类别的产品,这就是我想要的。这样做的问题是,如果产品属于某个类别且该类别产品已被删除,则IsDeleted标志将设置在单个展平的记录中,该记录将归结到设备。这是一个问题,因为产品本身尚未被删除,而是类别产品,但我的设备只看到一条记录,IsDeleted标志设置为删除它。因此,在这种情况下,我需要为展平产品添加一行以及已删除的信息,并且还需要该行的一行,就像它没有被删除一样,这样用户仍然可以在设备上搜索此产品。

希望我能清楚地解释清楚这一点,我一直在为此坚持一周。

1 个答案:

答案 0 :(得分:0)

如果你需要看两行,那么我希望在子查询中看到一个UNION ALL。我认为您需要包括所有产品以及所有未删除的产品类别。