如何从查询中捕获值并将其用作另一个查询中的值

问题描述 投票:2回答:1

我有一个在Python中运行的Postgres(redshift)查询,该查询输出一个字段及其值。我想运行另一个使用该查询中的值的查询。但是,当我运行以下代码时,它给我一个错误:

taskinstance.py:1051} ERROR - no results to fetch

这是我的代码:

def get_etl_recordd():
    pg_hook = PostgresHook(postgre_conn_id="postgres_default", schema='db1')
    connection = pg_hook.get_conn()
    nt_cur = connection.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
    atest_update_query = "select max(updated_at) from schema1.table1 group by updated_at order by updated_at asc limit 1;"
    nt_cur.execute(atest_update_query)
    result = nt_cur.fetchone()
    max_updated_at = result.max

    cursor2= connection.cursor()
    latest_update_query1 = "select * from schema1.table1 where updated_at <= '{}'; commit;".format(max_updated_at)
    cursor2.execute(latest_update_query1)

    d=cursor2.fetchone()
    connection.close()

关于为什么发生这种情况的任何想法? atest_updated_query中的值是一个时间戳记,latest_updated_query1实际上具有输出。任何帮助,将不胜感激。

这是我在Python / Airflow中运行的Postgres(Redshift)查询。

python postgresql amazon-redshift airflow mysql-python
1个回答
1
投票

我无法在您的代码中发现问题,但是您可以尝试使用get_firstPostgresHook方法。它应该可以完全实现您要实现的目标,并且可以肯定地在我们的气流/红移设置中起作用。

sql = "SELECT 1"

hook = PostgresHook(postgres_conn_id=self.postgres_conn_id, schema=self.database)

first_col_of_first_row = self.hook.get_first(sql)[0]
© www.soinside.com 2019 - 2024. All rights reserved.