python - SQLAlchemy - 将 where 子句添加到选择生成子查询

标签 python postgresql sqlalchemy

docs for Select.where 表示此方法应该将 WHERE 子句附加到现有的 SELECT 查询,但有时它似乎将 select 包装为子查询,从而导致ProgrammingError: (psycopg2.ProgrammingError) FROM 中的子查询必须有别名 错误。这似乎只发生在我试图过滤的选择在查询链的早期有一个连接时

# this works
my_select = select([tbl.c.id, tbl.c.my_col])
filtered = my_select.where(tbl.c.my_col == 'foo')

# this doesn't work, and seems to wrap the my_select in an additional subquery
j = tbl1.join(tbl2, tbl1.c.id == tbl2.c.id)
my_select = select([tbl1.c.id, tbl2.c.my_col]).select_from(j)
filtered = my_select.where(my_select.c.my_col == 'foo')

# Text representations will usually work as expected
j = tbl1.join(tbl2, tbl1.c.id == tbl2.c.id)
my_select = select([tbl1.c.id, tbl2.c.my_col]).select_from(j)
filtered = my_select.where("my_col = 'foo'")

最佳答案

我想我刚刚弄明白了。问题似乎是自引用列,所以

filtered = my_select.where(my_select.c.my_col == 'foo')

应该是

filtered = my_select.where(tbl2.c.my_col == 'foo')

以便它引用原始列对象而不是选择中的列。

这只是一个假设,如果其他人也可以验证,我们将不胜感激。

关于python - SQLAlchemy - 将 where 子句添加到选择生成子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35551562/

相关文章:

python - TypeError ("unsupported operand type(s) for/: ' 实例'和 'float'“

python - 根据条件 pandas python 在数据框中删除行

mysql - 一旦我想要整个数据库的 InnoDB,如何告诉 SQLAlchemy?

python - 使用 SQLAlchemy 思考特征

python - 迭代 n 个值

python - 创建仅限于本地主机连接的套接字

sql - 如何在 PostgreSql 中从秒获取年、月、日?

sql - PostgreSQL: CAST() as money: 指定货币

mysql - 使用外部数据包装器在 PostgreSQL 中删除外部模式

python - SQLAlchemy中,dict更新方法如何与ORM交互?