How to execute “left outer join” in SqlAlchemy

后端 未结 2 597
你的背包
你的背包 2020-11-30 03:01

I need to execute this query::

select field11, field12
from Table_1 t1
left outer join Table_2 t2 ON t2.tbl1_id = t1.tbl1_id
where t2.tbl2_id is null
         


        
2条回答
  •  时光说笑
    2020-11-30 03:36

    q = session.query(Table1.field1, Table1.field2)\
        .outerjoin(Table2)\ # use in case you have relationship defined
        # .outerjoin(Table2, Table1.id == Table2.table_id)\ # use if you do not have relationship defined
        .filter(Table2.tbl2_id == None)
    

    should do it, assuming that field1 and field2 are from Table1, and that you define a relationship:

    class Table2(Base):
        # ...
        table1 = relationship(Table1, backref="table2s")
    

提交回复
热议问题