2014-09-22 106 views
2

有人知道如何在SQLAlchemy中生成嵌套连词吗?如何在SQLAlchemy中编写嵌套连词(OR和AND子句)?

我有类似这样的一些Python代码:

import sqlalchemy as sa 

a = sa.and_(mytable.col1 > 1, mytable.col2 < 3) 
b = sa.and_(mytable.col1 < 1, mytable.col4 == None) 
clause_args = [a, b] 
or_clauses = sa.or_(*clause_args) 
session.query(mytable).filter(mytable.status.in_([1,2,3,4])).filter(or_clauses) 

注意,这仅仅是一些伪证明我有语法问题。 不要太多地分析查询逻辑。我只是想找到一种方法如何在AND和OR块之间添加括号。 SQLAlchemy的产生与此类似SQL:

SELECT 
    id, status, name, col1, col2, col3, col4 
FROM mytable 
WHERE 
    status in (1,2,3,4) 
AND (col1 > 1 
    AND col2 < 3 
    OR col1 < 1 
    AND col4 is NULL); 

注意,AND条件具有OR值之间围绕逻辑没有括号和块:

AND (col1 > 1 
    AND col2 < 3 
    OR col1 < 1 
    AND col4 is NULL); 

我想强制使用括号中的过滤器or_和和连词。 我想圆括号条件,使SQL输出看起来像这样:

SELECT 
    id, status, name, col1, col2, col3, col4 
FROM mytable 
WHERE 
    status in (1,2,3,4) 
AND ((col1 > 1 
    AND col2 < 3) 
    OR (col1 < 1 
    AND col4 is NULL)); 

任何人都可以提出如何实现这一目标?

谢谢!

+0

到这里看看: http://stackoverflow.com/questions/26154009/how-to-nest-conjunctions-or -and和功能于sqlalchamey – user3745855 2014-10-02 13:50:40

回答

0

IIUC,因为AND优先于OR,所以不需要括号。

1

使用self_group()。文档链接:self_group

解决方案的例子看起来像

import sqlalchemy as sa 

a = sa.and_(mytable.col1 > 1, mytable.col2 < 3).self_group() 
b = sa.and_(mytable.col1 < 1, mytable.col4 == None).self_group() 
clause_args = [a, b] 
or_clauses = sa.or_(*clause_args) 
session.query(mytable).filter(mytable.status.in_([1,2,3,4])).filter(or_clauses)