【问题标题】:How to properly join same table multiple times using sqlalchemy core api?如何使用 sqlalchemy core api 多次正确连接同一个表?
【发布时间】:2015-06-09 15:50:09
【问题描述】:

我尝试使用 sqlalchemy core api 多次加入同一张表。

代码如下:

import sqlparse
import sqlalchemy as sa

meta = sa.MetaData('sqlite:///:memory:')

a = sa.Table(
    'a', meta,
    sa.Column('id', sa.Integer, primary_key=True),
)

b = sa.Table(
    'b', meta,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('x', sa.Integer, sa.ForeignKey(a.c.id)),
    sa.Column('y', sa.Integer, sa.ForeignKey(a.c.id)),
)

meta.create_all()

x = b.alias('x')
y = b.alias('y')

query = (
    sa.select(['*']).
    select_from(a.join(x, a.c.id == x.c.x)).
    select_from(a.join(y, a.c.id == y.c.y))
)

print(sqlparse.format(str(query), reindent=True))

最后一条语句产生以下输出:

SELECT *
FROM a
JOIN b AS x ON a.id = x.x,
            a
JOIN b AS y ON a.id = y.y

如果我尝试执行此查询 query.execute() 我会收到错误:

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) ambiguous column name: main.a.id [SQL: 'SELECT * \nFROM a JOIN b AS x ON a.id = x.x, a JOIN b AS y ON a.id = y.y']

问题是,我怎样才能摆脱, a?如果我尝试执行:

engine.execute('''
    SELECT *
    FROM a
    JOIN b AS x ON a.id = x.x
    JOIN b AS y ON a.id = y.y
''')

效果很好。

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:
    query = (
        sa.select(['*']).
        select_from(a
                    .join(x, a.c.id == x.c.x)
                    .join(y, a.c.id == y.c.y)
                    )
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2015-10-26
      • 2015-04-01
      • 2012-05-23
      • 1970-01-01
      • 2011-08-28
      相关资源
      最近更新 更多