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

sir*_*rex 5 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))
Run Code Online (Sandbox Code Playgroud)

最后一个语句产生以下输出

SELECT *
FROM a
JOIN b AS x ON a.id = x.x,
            a
JOIN b AS y ON a.id = y.y
Run Code Online (Sandbox Code Playgroud)

如果我尝试执行此查询,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']
Run Code Online (Sandbox Code Playgroud)

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

engine.execute('''
    SELECT *
    FROM a
    JOIN b AS x ON a.id = x.x
    JOIN b AS y ON a.id = y.y
''')
Run Code Online (Sandbox Code Playgroud)

它工作正常.

van*_*van 9

query = (
    sa.select(['*']).
    select_from(a
                .join(x, a.c.id == x.c.x)
                .join(y, a.c.id == y.c.y)
                )
)
Run Code Online (Sandbox Code Playgroud)