python - 如何使用 sqlalchemy 核心 api 多次正确连接同一个表?

标签 python sqlalchemy

我尝试使用 sqlalchemy 核心 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
''')

它工作正常。

最佳答案

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

关于python - 如何使用 sqlalchemy 核心 api 多次正确连接同一个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30736958/

相关文章:

python - 将字符串转换为不带 strptime 的日期时间对象

python - SQLAlchemy ORM 重构器的替代品

python - SQLAlchemy声明式: How to merge models and existing business logic classes

python - 添加成对产品

python - 在 SQLAlchemy 中按空值过滤 postgres JSON 列

python - 在 sqlalchemy 中向 s 选择添加空列

python - 默认检查同一个表的列

python - 访问共享网络驱动器和删除特定文件的最佳方法

python - 找到一对值的最大值并且需要不断重建的最有效的数据结构是什么?

python - TypeError: 'builtin_function_or_method' 对象不可下标