sql - 查找包含集合的记录
问题描述
我有 2 套 - 一套“attribute_A”和一套“attribute_B”。我只想获得这些“字段”,它们具有所有输入的属性(attrubute_A、attribute_B)。
假设我们有:
TABLE 1 (tab1)
id name
1 'clients'
2 'employees'
TABLE 2 (tab2)
user_id tab1_id shop
1 1 shop_A
2 2 shop_C
3 1 shop_B
3 2 shop_B
TABLE 3 (tab3)
table1_id permissions
1 buying
2 buying
2 working
我编写了一个查询,该查询对一组参数正确工作:
SELECT tab2.user_id FROM tab2
(... JOINS ...)
WHERE tab3.permissions IN ('working', 'buying')
GROUP BY tab2.user_id
HAVING count(DISTINCT tab3.permissions) = 2
编辑:假设我们有商店,用户组(客户,员工),每个组都有一定的权限。
现在我想只选择获得购买和使用shop_A和shop_C的权限的这些成员(user_ids)。
解决方案
如果我理解正确,您可以使用intersect
:
SELECT t2.user_id
FROM tab2 t2 JOIN
tab3 t3
ON t2.tab1_id = t3.tab1_id
WHERE tab3.permissions IN ('working', 'buying')
GROUP BY tab2.user_id
HAVING count(DISTINCT tab3.permissions) = 2
INTERSECT
SELECT tab2.user_id
FROM tab2
WHERE tab2.shop IN ('shop_A', 'shop_C')
GROUP BY tab2.user_id
HAVING count(DISTINCT tab2.shop) = 2
推荐阅读
- c# - 使用 AzureDevops、虚拟测试服务器和 Selenium 如何让我的测试脚本上传文件?
- oracle-apex - Oracle APEX 交互式网格中页脚的奇怪行为
- c# - SQL 参数化与使用 string.format
- c# - Service Fabric - 每个服务实例的动态资源管理
- c# - 在 .NET 应用程序中管理数据库访问密码?
- sql - 在 PostgreSQL 中按多个内连接的条件计数
- python-3.x - 镶木地板文件中的python Schema不同
- python-3.x - 类对象不继承其他类属性
- python - 尝试在 Raspberry Pi2 (Stretch) 上使用 Selenium
- python - Python smtplib:无法向手机发送短信