我想根据复合键选择一堆不同的记录。在SQL
中我写了这样的东西:
SELECT * FROM security WHERE (
exchange_code = 'exchange_code_1' AND code = 'code_1')
OR (exchange_code = 'exchange_code_2' AND code = 'code_2')
...
OR (exchange_code = 'exchange_code_N' AND code = 'code_N')
)
使用SQLAlchemy
我想使用过滤子句,如:
query = sess.query(Security)
[query.filter(
and_(Security.exchange_code == security.exchange_code,
Security.code == security.code)
) for security in securities]
result = query.all()
问题是filter
和where
使用AND而不是OR加入子句...是否有某种方法可以将过滤器与OR一起使用?
或者我唯一的选择是生成一堆单独的选择和UNION
它们?类似的东西:
first = exchanges.pop()
query = reduce(lambda query, exchange: query.union(exchange.pk_query),
first.pk_query())
query.all()