如何执行“左外连接"在 SqlAlchemy 中 [英] How to execute "left outer join" in SqlAlchemy

查看:72
本文介绍了如何执行“左外连接"在 SqlAlchemy 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行这个查询::

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

我在 python 中有这些类:

I had these classes in python:

class Table1(Base):
   ....

class Table2(Base):
   table_id =  Column(
        Integer,
        ForeignKey('Table1.id', ondelete='CASCADE'),
    )
    ....

我如何从下面到达上面?

How do I get to the above from the below?

推荐答案

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)

应该这样做,假设 field1field2 来自 Table1,并且您定义了一个关系:

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")

这篇关于如何执行“左外连接"在 SqlAlchemy 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆