查找包含记录的记录

问题描述 投票:0回答:1

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

sql oracle
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.