MS SQL-从多对多表中选择数据,其中列的值与所有给定值匹配

时间:2019-02-11 05:42:24

标签: sql sql-server

我有一个名为SUPPLIER_CATEGORY的表,作为SUPPLIER和CATEGORY表之间的多对多关系。我想要的是从SUPPLIER_CATEGORY表中获取SUPPLIER_ID,该表与给定的所有CATEGORY_ID相匹配。

例如,请考虑下表

SUPPLIER_ID    CATEGORY_ID

101                1
101                2
102                1
102                3
103                1
103                2
103                3

如果我想获取具有CATEGORY_ID 1和2的SUPPLIER_ID,则查询应返回SUPPLIER_ID 101和103,但不返回102,因为它具有CATEGORY_ID =1。因为它不包含CATEGORY_ID2。希望它有意义。

编辑:

注意:CATEGORY_ID可以是两个以上的数字。

谢谢。

4 个答案:

答案 0 :(得分:2)

对于给定的样本数据,下面将是查询。

select supplier_id
from <tableName>
where category_id in (1, 2)
group by supplier_id
having count(*) > 1

答案 1 :(得分:1)

您可以在下面尝试-

select SUPPLIER_ID from tablename where CATEGORY_ID in (1,2)
group by SUPPLIER_ID  having count(distinct CATEGORY_ID)=2

答案 2 :(得分:1)

DECLARE @catIds varchar(max)='1,2'
DECLARE @SplitOn CHAR = ','

-------------- spliting all CATEGORY_ID ---- 
DECLARE @RtnTable TABLE (catId int )
DECLARE @Count int
SET @Count = 1
WHILE (CHARINDEX(@SplitOn,@catIds)>0)

BEGIN
    INSERT INTO @RtnTable (catId)

SELECT
    Value = LTRIM(RTRIM(SUBSTRING(@catIds,1,CHARINDEX(@SplitOn,@catIds)-1)))

    SET @catIds = SUBSTRING(@catIds,CHARINDEX(@SplitOn,@catIds)+LEN(@SplitOn),LEN(@catIds))
Set @Count = @Count + 1
END

INSERT INTO @RtnTable (catId)

SELECT
    Value = LTRIM(RTRIM(@catIds))

-------------------------------------------------


--------------- main part ---------------
SELECT  [SUPPLIER_ID]      
  FROM [EmployeeDb].[dbo].[SUPPLIER_CATEGORY]
  WHERE CATEGORY_ID in(SELECT * from @RtnTable)
  GROUP BY [SUPPLIER_ID]
  HAVING (count(CATEGORY_ID)=  @Count )

--------------- main part ---------------

答案 3 :(得分:0)

您可以将此程序化解决方案用作用户输入。

DECLARE @ids NVARCHAR(MAX) = N'1,2'
DECLARE @input_xml XML = Cast('<root><x>'+ Replace(@ids, ',', '</x><x>')+ '</x></root>' AS XML) 

DECLARE @list_to_table TABLE(Id BIGINT)

INSERT INTO @list_to_table
SELECT DISTINCT f.x.value('.', 'BIGINT') AS Id
FROM @input_xml.nodes('/root/x') f(x);

SELECT sc.supplier_id      
FROM supplier_category sc
INNER JOIN @list_to_table ltt on sc.category_id = ltt.id
GROUP BY sc.supplier_id 
HAVING count(DISTINCT sc.category_id ) = (SELECT COUNT(1) FROM @list_to_table);