Skip to main content
 首页 » 编程设计

python之如何将许多 "x AND y"条件与 WHERE 子句的 OR 结合起来

2024年10月17日8findumars

我有一个类似于下面的多对多联结表:

        FooBar 
----------------------- 
id    | foo_id | bar_id 
1     |    1   |    1 
2     |    1   |    2 
3     |    2   |    3 
4     |    3   |    4 

和(foo_id, bar_id)的列表,例如:

items = [(1, 1), (1, 2), (2, 3), (3, 4) 

如何在 SQLAlachemy 中执行以下查询?

SELECT id 
FROM foo_bar 
WHERE (foo_id = 1 AND bar_id = 1) 
   OR (foo_id = 1 AND bar_id = 2) 
   OR (foo_id = 2 AND bar_id = 3) 
   OR (foo_id = 3 AND bat_id = 4) 

我尝试了以下变体,但它们都返回一个仅包含 AND 的 WHERE 子句

from sqlalchemy import and_, or_ 
q = session.query(FooBar) 
for item in items: 
    q = q.filter(or_(and_(FooBar.foo_id == item[0], FooBar.bar_id == item[1]))) 
 
print q.statement 
for item in  

请您参考如下方法:

问题是用单个表达式调用 or_() 基本上只是表达式,因为没有任何东西可以进行 OR 操作。多次调用Query.filter()追加与 AND 结合的新谓词。将迭代移动到 filter(or_()) 内的项目上:

q = q.filter(or_(*(and_(FooBar.foo_id == foo_id, FooBar.bar_id == bar_id) 
                   for foo_id, bar_id in items))) 

这会生成一个生成器表达式,然后将其解压缩为 or_() 的位置参数。

如果使用支持复合 IN 结构的后端,例如 Postgresql 和 MySQL,您可以将其替换为 tuple_().in_ :

from sqlalchemy import tuple_ 
 
... 
 
q = q.filter(tuple_(FooBar.foo_id, FooBar.bar_id).in_(items))