2014-09-22 108 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)