如何在 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

原文由 user1742188 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答

isouter=True 标志将产生一个 LEFT OUTER JOINLEFT 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)

原文由 user1742188 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题