如何在SQLALchemy中执行左连接?

use*_*188 11 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_
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有:

(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)))
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何进行加入LEFT JOIN.

use*_*188 11

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)))
Run Code Online (Sandbox Code Playgroud)

声明性示例:

session = scoped_session(sessionmaker())
session.query(Model).join(AnotherModel, AnotherModel.model_id == Model.id, isouter=True)
Run Code Online (Sandbox Code Playgroud)

  • 我使用了第二个解决方案(声明性示例),并且效果非常好,喜欢它! (2认同)

Ido*_*doS 11

选项 1 - LEFT JOIN 并从两个表中选择所有列

# Query the db
results = db.session.query(Table_1, Table_2).join(
      Table_2, Table_2.column_name == Table_1.column_name, 
      isouter=True).all()
# Iterate results and do stuff
for result in results:
    try:
        # Use [0] for accesing table_1 columns (left table) and use [1] for accesing table_2 columns (right table)
        print(result[0].column_name_x)
        print(result[0].column_name_y)
        print(result[1].column_name_x)
        print(result[1].column_name_y)
     except Exception as e:
        print(str(e))
Run Code Online (Sandbox Code Playgroud)

选项 2 - LEFT JOIN 并从两个表中选择一些列

# Query the db
results = db.session.query(Table_1.column_name_x, Table_1.column_name_y Table_2.column_name_z).join(Table_2, Table_2.column_name == Table_1.column_name, isouter=True).all()
# Iterate results and do stuff
for result in results:
    try:
        # Use dot notation for accesing column from any table
        print(result.column_name_x)
        print(result.column_name_y)
        print(result.column_name_z)
    except Exception as e:
        print(str(e))
Run Code Online (Sandbox Code Playgroud)


mel*_*r55 10

isouter 的使用方法如下:

select_from(db.join(Table1, Table2, isouter=True).join(Table3, isouter=True)) 
Run Code Online (Sandbox Code Playgroud)