2013-07-17 67 views
-1

我的Product记录使用ProductCategory表与多对多记录到Category记录。选择所有类别中包含的产品

在存储过程中,我有两个或更多CategoryId值的列表(CategoryIds)。如何查询Product表并仅返回与CategoryIds中的类别相关的产品?我无法弄清楚我是否需​​要加入或选择或..?

 
SELECT 
    * 
FROM 
    Product as P 
    -- I can't join here because the relation is many-to-many 
WHERE 
    -- This only checks if there is one category to which the product is related 
    (SELECT Count(C.CategoryId) FROM ProductCategory as PC INNER JOIN Category as C ON PC.CategoryId = C.CategoryId WHERE PC.ProductId = P.ProductId AND PC.CategoryId IN (@CategoryIds)) > 0 

任何帮助,非常感谢!

+0

就是 “CategoryIds” CSV参数? – gotqn

+0

您的查询似乎很简单。您应该包含更多信息。像什么是@categoryId,它是如何定义的。你使用的是哪个版本的sql server,你的表格是如何定义的 –

+0

包括测试数据和预期结果也可能是一个想法,以防止我们猜测并浪费时间在错误的答案上 –

回答

0

下面的语句将返回你所有的产品在CSV参数类别规定:

DECLARE @Products TABLE 
(
    [ProductID] INT 
    ,[ProductName] NVARCHAR(32) 
) 

DECLARE @Categories TABLE 
(
    [CategoryID] INT 
    ,[CategotyName] NVARCHAR(32) 
) 

DECLARE @ProductCategory TABLE 
(
    [ProductID] INT 
    ,[CategoryID] INT 
) 


INSERT INTO @Products ([ProductID], [ProductName]) 
VALUES (1, 'Product 1') 
     ,(2, 'Product 2') 
     ,(3, 'Product 3') 
     ,(4, 'Product 4') 

INSERT INTO @Categories ([CategoryID], [CategotyName]) 
VALUES (1, 'Category 1') 
     ,(2, 'Category 2') 
     ,(3, 'Category 3') 

INSERT INTO @ProductCategory ([ProductID], [CategoryID]) 
VALUES (1, 1) 
     ,(1, 2) 
     ,(1, 3) 
     ,(2, 1) 
     ,(2, 2) 
     ,(3, 1) 
     ,(4, 2) 
     ,(4, 3) 

DECLARE @CategoriesCSV NVARCHAR(MAX) = '1,2' 


DECLARE @CategoriesXML XML = N'<r><![CDATA[' + REPLACE(@CategoriesCSV, ',', ']]></r><r><![CDATA[') + ']]></r>' 

;WITH DataSource AS 
(
    SELECT DISTINCT CAST(Tbl.Col.value('.', 'float') AS BIGINT) AS [CategoryID] 
    FROM @CategoriesXML.nodes('//r') Tbl(Col) 
    WHERE ISNUMERIC(Tbl.Col.value('.', 'varchar(max)')) = 1 
) 
SELECT C.[CategoryID] 
     ,C.[CategotyName] 
     ,P.[ProductID] 
     ,P.[ProductName] 
FROM @Categories C 
INNER JOIN DataSource DS 
    ON C.[CategoryID] = DS.[CategoryID] 
INNER JOIN @ProductCategory PC 
    ON C.[CategoryID] = PC.[CategoryID] 
INNER JOIN @Products P 
    ON PC.[ProductID] = P.[ProductID] 

从上面的查询结果是:

enter image description here

+0

我不需要在_all_类别中_all_产品,而是_only_处于_all_类别的产品。 – ReFocus

+0

@ReFocus通过我使用的示例数据,精确显示您想要的输出结果,并向您展示如何获取它。 – gotqn

相关问题