检查列值是否在子查询中

问题描述 投票:0回答:2

我有3个表Product Category和ProductCategory。

产品表:

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))

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

sql sql-server
2个回答
5
投票

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

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

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/

© www.soinside.com 2019 - 2024. All rights reserved.