检索主键是元组 (a,b) 且所有行 (a,b') 必须存在于给定列表的 b' 值的列值

Retrieving the a column value where the primary key is a tuple (a,b) and where all rows (a,b') must exist for a given list for b' values

我有一个 A|B|C 形式的 table,其中元组 (a,b) in (A,B) 是主键。我有 B 的值列表 (BVAL) 并且我需要 A 列中的元素,其中 b' in BVAL 的每个类型 (a,b') 值的行条目存在。

目前我已经实现了一个脚本,该脚本检索 BVAL 的第一个元素的第一个 all (a,b''),然后迭代并优化列表直到 BVAL 的最后一个元素。我相信它在大型数据库中会很慢,并且相信存在更快的解决方案。非常感谢任何帮助。

假设我们有以下 table:

+---+---+
| A | B |
+---+---+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 2 | 1 |
| 2 | 2 |
| 3 | 1 |
+---+---+

如果 BVALs 列表由 (1,2) 组成,则查询应该 return 1 和 2

这是你想要的吗?

select distinct a
from t
where b in ( . .  . );  -- list of b values here

我知道您想要 a 具有所有 b 值。如果是这样,您可以使用 group byhaving:

select a
from mytable
where b in (1, 2)   -- either value
group by a
having count(*) = 2 -- both match