【问题标题】:Using format in two queries in sql在sql的两个查询中使用格式
【发布时间】:2020-04-10 18:15:43
【问题描述】:

我有一个查询,我使用 except。我想在运行选择查询时以格式发送表路径。

query_2="""select * 
           from {}.{} 
           where date(etl_date) = current_date 
           except select * 
                  from {}_test.{} 
                  where date(etl_date)=current_date"""
       .format(liste[0],liste[1])

但我自然会收到这样的错误。

IndexError: 元组索引超出范围

我还能如何在这里使用格式功能?谢谢...

【问题讨论】:

  • 该错误表明元组元素listenull 或仅包含一个值,并且您尝试访问的元素比它包含的更多。
  • 如果您的问题得到解答,请将其标记为solved

标签: python sql database format psycopg2


【解决方案1】:

不要对 SQL 查询使用简单的格式;对表、字段使用sql.Identifier,并使用execute 方法的second argument 传递变量(如果需要)。

from psycopg2.sql import Identifier, SQL
connection = psycopg2.connect("...")
cursor = connection.cursor()
suffix = "_test"
identifiers = [Identifier("some_schema"), Identifier("some_table"), Identifier("other_schema%s" % suffix), Identifier("other_table")]
query_2 = SQL("""select * from {}.{} where date(etl_date) = current_date 
              except select * from {}.{} where date(etl_date)=current_date""").format(*identifiers)
print(query_2.as_string(cursor))  # if you want to see the final query
cursor.execute(query_2)

输出

select * from "some_schema"."some_table" where date(etl_date) = current_date
except select * from "other_schema_test"."other_table" where date(etl_date)=current_date

这假设您在同一个数据库中有多个架构,因为您无法在 PostgreSQL 中轻松进行跨数据库查询。

【讨论】:

  • 感谢您的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
相关资源
最近更新 更多