如果我有一个PERMISSIONS看起来像这样的表:
PERMISSIONS
PERSON PERMISSION ------ ---------- Bob red John red John blue Mary red Mary blue Mary yellow
还有一个THINGS表,如下所示:
THING PERMISSION ----- ---------- apple red eggplant red eggplant blue
我正在尝试提出一个纯SQL查询,该查询可以让我找出什么PERSON可以访问什么THING。基本上,我想要一个看起来像这样的查询:
PERSON
THING
SELECT person FROM ... vague handwaving here ... WHERE thing = 'eggplant'
并返回“ John”和“ Mary”。关键是访问事物所需的许可数量是任意的。
我觉得这应该很明显,但是我无法提出一个优雅的解决方案。首选与Oracle兼容的解决方案。
编辑:
Kosta和JBrooks的解决方案效果很好。以下是Kosta解决方案的修改版本,该解决方案仅两次命中索引,而不是Kosta的3倍和JBrooks的4倍(尽管我同意JBrooks的观点,这可能是不必要的优化)。
SELECT p.person, num_permission, COUNT(p.person) FROM permissions p INNER JOIN ( SELECT permission, COUNT(1) OVER (PARTITION BY thing) AS num_permission FROM things WHERE thing = 'eggplant' ) t ON t.permission = p.permission GROUP BY p.person, num_permission HAVING COUNT(p.person) = num_permission
select person from permissions where permission in (select permission from things where thing='eggplant') group by person having count(person) = (select count(permission) from things where thing='eggplant')