[英]SELECT returning rows when executed from SQL client but none when executed from SQLAlchemy
I have the following query:我有以下查询:
SELECT sum(x), sum(y)
FROM stats s1
WHERE fk_id = :id
AND EXISTS (
SELECT
FROM stats s2
WHERE s2.fk_id = s1.fk_id
AND s2.datetime::date = (now() - '1 day'::interval)::date
)
The second condition ensures that there are stats from yesterday.第二个条件确保有昨天的统计数据。 Otherwise it returns no results.
否则它不返回任何结果。
When I execute it from a SQL client (ie DBeaver), it returns 1 row as expected, eg 12.3, 45.6
.当我从 SQL 客户端(即 DBeaver)执行它时,它按预期返回 1 行,例如
12.3, 45.6
。 When I execute the query from SQLAlchemy, ie session.execute(query, {"id": id}).first()
, it returns (None, None)
.当我从 SQLAlchemy 执行查询时,即
session.execute(query, {"id": id}).first()
,它返回(None, None)
。 Same query, same database, same id.相同的查询,相同的数据库,相同的 ID。
I tried running it from SQLAlchemy without the EXISTS
condition , and in this case, it returns 1 row.我尝试在没有
EXISTS
条件的情况下从 SQLAlchemy 运行它,在这种情况下,它返回 1 行。 So it's something related to the second condition when executed from different places.所以当从不同的地方执行时,它与第二个条件有关。
Why does the EXISTS
condition return TRUE
when executed from a SQL client but FALSE
from SQLAlchemy?为什么
EXISTS
条件从 SQL 客户端执行时返回TRUE
,但从 SQLAlchemy 执行时返回FALSE
?
You must SELECT
something, even in a subquery, even if it makes no sense:你必须
SELECT
一些东西,即使在子查询中,即使它没有意义:
SELECT SUM(s1.x), SUM(s1.y)
FROM stats s1
WHERE s1.fk_id = :id
AND EXISTS (
SELECT 'OMG!' -- <<-- HERE
FROM stats s2
WHERE s2.fk_id = s1.fk_id
AND s2.datetime::date = (now() - '1 day'::interval)::date
)
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.