首页 > 解决方案 > 查询以选择类别 ID,其中至少存在所有子类别 ID。(SQL 服务器)

问题描述

我有两个表,#table1(subCatId)和#table2(categoryId,subCatId)。

#table1

subCatId
---------
    1
    2
    3
    4

#table2

categoryId   subCatId
---------------------
    1            1
    1            2
    1            3
    2            1
    2            2
    2            3
    2            4
    2            5
    3            1
    3            2
    3            5
    3            4
    4            1
    4            2
    4            3
    4            4

输出:

categoryId 
-----------
    2
    4  

因为至少所有 subCatId (1, 2, 3, 4) 都存在于这两个类别中。

标签: sqlsql-serversql-server-2008

解决方案


您可以使用group byhaving

select t2.categoryId
from #table2 t2
group by t2.categoryId
having count(*) = (select count(*) from #table1);

这假定和之间存在适当的外键关系,#table2.subCatId并且#table1.subCatId没有重复项。
如果不是这种情况,更通用的解决方案是:

select t2.categoryId
from #table2 t2 join
     #table1 t1
     on t2.subCatId = t1.subCatId  -- filter to be sure only matching subCatId are counted
group by t2.categoryId
having count(distinct t2.subCatId) = (select count(*) from #table1);

推荐阅读