首页 > 解决方案 > 查找包含集合的记录

问题描述

我有 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)。

标签: sqloracle

解决方案


如果我理解正确,您可以使用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

推荐阅读