如何在SQLALchemy中执行左连接?

时间:2016-09-21 14:24:26

标签: python sql sqlalchemy

我有一个SQL查询,它会在几个表上执行一系列左连接:

SELECT
<some attributes>
FROM table1 t1
INNER JOIN table2 t2
      ON attr = 1 AND attr2 = 1
LEFT JOIN table3 t3
    ON t1.Code = t2.Code AND t3.Date_ = t1.Date_
LEFT JOIN tabl4 t4
    ON t4.Code = t1.code AND t4.Date_ = t1.Date_

到目前为止,我有:

(sa.select([idc.c.Code])
            .select_from(
                t1.join(t2, and_(t1.c.attr == 1, t2.c.attr2 = 1))
                .join(t3, t3.c.Code == t1.c.Code)))

但我无法弄清楚如何将加入设为LEFT JOIN

2 个答案:

答案 0 :(得分:5)

isouter=True标记将生成LEFT OUTER JOIN,与LEFT JOIN相同。

使用您的代码:

(sa.select([idc.c.Code])
        .select_from(
            t1.join(t2, and_(t1.c.attr == 1, t2.c.attr2 = 1))
            .join(t3, t3.c.Code == t1.c.Code, isouter=True)))

声明示例:

session = scoped_session(sessionmaker())
session.query(Model).join(AnotherModel, AnotherModel.model_id == Model.id, isouter=True)

答案 1 :(得分:2)

以下是如何使用isouter:

select_from(db.join(Table1, Table2, isouter=True).join(Table3, isouter=True))