sql - 查询以选择类别 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) 都存在于这两个类别中。
解决方案
您可以使用group by
和having
:
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);
推荐阅读
- git - 我正在将 git hub 存储库克隆到 Cpanel git 版本控制我收到 term 15 错误
- python - 使用 set_index 函数时出现语法错误
- arkit - 在 RealityKit 中可视化检测到的平面问题
- ansible - 在 yaml 文件中定义的主机上运行任务,而不是使用 ansible 进行清单
- emacs - 如果不立即向上移动,Emacs 26.3 滚动条拒绝向上移动
- git - 如何让两个签出的 git 存储库相互同步?
- python - 获取上面行的结果
- firebase - 在 Flutter 中使用 Firebase 连接到 Facebook 时令牌无效
- javascript - 为什么我的 Node.js ServerResponse **由 Proxy 包装**没有响应?
- c++ - 为什么这会导致分段错误?