简体   繁体   English

SELECT 从 SQL 客户端执行时返回行,但从 SQLAlchemy 执行时返回行

[英]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.

相关问题 如何从 SQLAlchemy 中检索执行的 SQL 代码 - How to retrieve executed SQL code from SQLAlchemy 从 pgsql 中循环执行的查询返回行 - Returning rows from queries executed in loop in pgsql 从服务器执行时,Python脚本崩溃 - Python script crashes when executed from server 从另一个线程调用时未执行的语句 - statements not executed when called from another thread UnicodeEncodeError-在Spyder中有效,但在从终端执行时无效 - UnicodeEncodeError - works in Spyder but not when executed from terminal 使用 SQLAlchemy 执行更新语句不会更新行,但在 MySQL 工作台中执行时语句可以完美运行 - Executing update statement with SQLAlchemy does not update rows, but statement works perfectly in when executed in MySQL Workbench Selenium-Python-ChromeBrowser启动在python IDE中执行时有效,但从PyDev(Eclipse)执行时不起作用 - Selenium-Python-ChromeBrowser Launch works when executed in python IDE but it does not when executed from PyDev(Eclipse) 数据库 object 从另一个 python 脚本执行 SQL-INSERT 查询失败 - Failing SQL-INSERT query when it is executed by a database object from another python script python脚本可从命令行运行,但无法从Web应用程序执行时运行 - python script works from command line but not when it is executed from webapplication PyQt4示例从IDLE工作,但从npp执行时不工作 - PyQt4 example working from IDLE, but not when executed from npp
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM