7

我需要做这个查询:

SELECT *
FROM tbl_member
WHERE (member_type==1 AND member_status==1)
   OR (member_type==2 and member_status==2)

我试过了:

q=session.query(tbl_member) \
  .filter(or_(and_(tbl_member.member_type==1,tbl_member.member_status==1), \
              and_(tbl_member.member_type==2,tbl_member.member_status==2)))

q=session.query(tbl_member) \ 
  .filter(or_((and_(tbl_member.member_type==1,tbl_member.member_status==1)), \
              (and_(tbl_member.member_type==2,tbl_member.member_status==2))))

查询sql还是这样的:

SELECT *
FROM tbl_member
WHERE member_type==1 AND member_status==1 OR member_type==2 AND member_status==2

我应该怎么做?

4

1 回答 1

7

查询在语义上是相同的,因为AND优先于OR,因此
WHERE Cond1 AND Cond2 OR Cond3 AND Cond4将产生与 相同的结果
WHERE (Cond1 AND Cond2) OR (Cond3 AND Cond4)

如果您尝试相反的方式(切换or_and_在您的代码中),您会注意到sqlalchemy确实会生成括号。

于 2013-03-05T08:05:18.207 回答