SQLAlchemy correlated subquery TypeError: Boolean value of this clause is not defined
SQLAlchemy correlated subquery TypeError: Boolean value of this clause is not defined
我需要编写一个 Python SQLAlchemy 代码来转换此 SQL 查询,但我找不到在 SQL Alchemy 中执行此查询的有意义的方法。
SELECT *
FROM alpha AS X
WHERE X.index = (
SELECT
MAX(index)
FROM
alpha AS Y
WHERE
X.question = Y.question
AND X.person = Y.person
)
我试过这样,但我一直收到错误 TypeError: Boolean value of this clause is not defined
(alpha
是 Table)。
from sqlalchemy.orm import aliased
from sqlalchemy import func, and_
X = aliased(alpha)
Y = aliased(alpha)
conn.execute(
select(X).where(
X.c.index
== select(func.max(X.c.index))
.where(
and_(
X.c.question == Y.c.question,
X.c.person == Y.c.person,
)
)
.correlate(X)
)
)
我做错了什么?
我认为您真的只需要使用 scalar_subquery()。据我了解,关联会自动发生,如果 SQLAlchemy 无法分辨您的意思,您只需要 correlate
。
代码
alpha = Table("alpha", metadata,
Column("id", Integer, primary_key=True),
Column("question", String),
Column("person", String),
Column("index", Integer),)
Base.metadata.create_all(engine)
with Session(engine) as session:
X = aliased(alpha, name='X')
Y = aliased(alpha, name='Y')
q = select(X).where(
X.c.index
== select(func.max(X.c.index))
.where(
and_(
X.c.question == Y.c.question,
X.c.person == Y.c.person,
)
).scalar_subquery()
)
print (q)
SQL
SELECT "X".id, "X".question, "X".person, "X".index
FROM alpha AS "X"
WHERE "X".index = (SELECT max("X".index) AS max_1
FROM alpha AS "Y"
WHERE "X".question = "Y".question AND "X".person = "Y".person)
这是使用 Postgresql 和 SQLAlchemy 1.4.31。
我需要编写一个 Python SQLAlchemy 代码来转换此 SQL 查询,但我找不到在 SQL Alchemy 中执行此查询的有意义的方法。
SELECT *
FROM alpha AS X
WHERE X.index = (
SELECT
MAX(index)
FROM
alpha AS Y
WHERE
X.question = Y.question
AND X.person = Y.person
)
我试过这样,但我一直收到错误 TypeError: Boolean value of this clause is not defined
(alpha
是 Table)。
from sqlalchemy.orm import aliased
from sqlalchemy import func, and_
X = aliased(alpha)
Y = aliased(alpha)
conn.execute(
select(X).where(
X.c.index
== select(func.max(X.c.index))
.where(
and_(
X.c.question == Y.c.question,
X.c.person == Y.c.person,
)
)
.correlate(X)
)
)
我做错了什么?
我认为您真的只需要使用 scalar_subquery()。据我了解,关联会自动发生,如果 SQLAlchemy 无法分辨您的意思,您只需要 correlate
。
代码
alpha = Table("alpha", metadata,
Column("id", Integer, primary_key=True),
Column("question", String),
Column("person", String),
Column("index", Integer),)
Base.metadata.create_all(engine)
with Session(engine) as session:
X = aliased(alpha, name='X')
Y = aliased(alpha, name='Y')
q = select(X).where(
X.c.index
== select(func.max(X.c.index))
.where(
and_(
X.c.question == Y.c.question,
X.c.person == Y.c.person,
)
).scalar_subquery()
)
print (q)
SQL
SELECT "X".id, "X".question, "X".person, "X".index
FROM alpha AS "X"
WHERE "X".index = (SELECT max("X".index) AS max_1
FROM alpha AS "Y"
WHERE "X".question = "Y".question AND "X".person = "Y".person)
这是使用 Postgresql 和 SQLAlchemy 1.4.31。