检索主键为元组 (a,b) 且 b' 值的给定列表必须存在所有行 (a,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

提问人:Cherry Toska 提问时间:9/3/2020 最后编辑:timnavigateCherry Toska 更新时间:9/3/2020 访问量:64

问:

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

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

假设我们有下表:

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

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

python sql postgresql 计数 psycopg2

评论

0赞 Gordon Linoff 9/3/2020
请提供样本数据和预期结果。你的解释很难理解。

答:

1赞 Gordon Linoff 9/3/2020 #1

这是你想要的吗?

select distinct a
from t
where b in ( . .  . );  -- list of b values here
2赞 GMB 9/3/2020 #2

我知道你想要具有所有值的 s。如果是这样,您可以使用 and :abgroup byhaving

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