如何使用sqlalchemy core api多次正确连接同一个表?

时间:2015-06-09 15:50:10

标签: python sqlalchemy

我正在尝试使用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
''')

工作正常。

1 个答案:

答案 0 :(得分:6)

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