查找包含集的记录

时间:2019-12-16 10:27:50

标签: sql oracle

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

1 个答案:

答案 0 :(得分:0)

如果我理解正确,则您使用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
相关问题