【问题标题】:How to perform a left join in SQLALchemy?如何在 SQLALchemy 中执行左连接?
【发布时间】:2017-01-29 20:51:48
【问题描述】:

我有一个 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

【问题讨论】:

  • 您可以使用outerjoin 代替join
  • outerjoin 不是 join 的替代品。我需要左连接。

标签: python sql sqlalchemy


【解决方案1】:

isouter=True 标志将产生一个与LEFT JOIN 相同的LEFT OUTER 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)

【讨论】:

  • 我使用了第二种解决方案(声明式示例),效果很好,喜欢它!
【解决方案2】:

isouter的使用方法如下:

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

【讨论】:

    猜你喜欢
    • 2014-11-26
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2011-06-05
    • 2018-04-08
    • 2021-07-25
    相关资源
    最近更新 更多