1

我有 3 个表产品类别和产品类别。

产品表:

ProductID ProductName
1             P1
2             P2
3             P3

类别表:

CategoryID CategoryName
1              C1
2              C2
3              C3

产品分类:

ProductID CategoryID
1            1
1            2
1            3
2            3
3            1
3            2

我需要一个返回超过 1 个类别的产品的查询。根据上面的表格数据,结果将是:

ProductID     ProductName
    1             P1
    3             P3  

所以我写了一个查询来获取所有具有多个 CategoryID 的 ProductID,如下所示:

select ProductID,count(CategoryID)    
from ProductCategory   
group by Productid   
having count(CategoryID)>1)  

但是,当我尝试使用以下查询显示产品详细信息时,出现错误:

select *
from Product
where ProductID in (
    select ProductID,count(CategoryID)  
    from ProductCategory 
    group by Productid 
    having count(CategoryID)>1))

我的查询错了吗?我如何获得属于多个类别的所需产品详细信息?

4

2 回答 2

6

删除COUNT()子查询中的 。使用 onIN子句时,子查询的结果必须只有一个返回列。

SELECT  *
FROM    Product
WHERE   ProductID IN 
        (
            SELECT  ProductID
            FROM    ProductCategory
            GROUP   BY Productid
            HAVING  count(CategoryID) > 1
        ) 

或通过使用JOIN

SELECT  a.*
FROM    Product a
        INNER JOIN 
        (
            SELECT  ProductID
            FROM    ProductCategory
            GROUP   BY Productid
            HAVING  count(CategoryID) > 1
        ) b ON a.ProductID = b.ProductID
于 2013-04-05T13:17:20.547 回答
0

您可以尝试在 SQL Server 中使用 CROSS APPLY 运算符

SELECT DISTINCT C.ProductID,C.ProductName,A.CategoryID,A.Total
FROM Product C
CROSS APPLY (
    Select CA.CategoryID,Total=COUNT(*)
    From ProductCategory CA
    Where C.ProductID=CA.ProductID
    Group By CA.CategoryID Having COUNT(*)>1
) AS A
ORDER BY A.Total DESC

看看:http ://explainextended.com/2009/07/16/inner-join-vs-cross-apply/

于 2013-04-05T13:45:58.247 回答