如何执行"左外连接"在SqlAlchemy中

时间:2014-10-01 13:15:51

标签: python sql sqlalchemy

我需要执行此查询::

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中有这些类:

class Table1(Base):
   ....

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

如何从下面获得上述内容?

2 个答案:

答案 0 :(得分:49)

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,并且您定义了一个关系:

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

答案 1 :(得分:5)

您也可以仅使用SQLAlchemy Core执行此操作:

session.execute(
    select(['field11', 'field12'])
    .select_from(
        Table1.outerjoin(Table2, Table1.tbl1_id == Table2.tbl1_id))
    .where(Table2.tbl2_id.is_(None))
)

PS .outerjoin(table, condition)相当于.join(table, condition, isouter=True)