在 sql 中的两个查询中使用格式

Using format in two queries in sql

我有一个查询,我使用 except.I 想在 运行 select 查询时以格式发送 table 路径。

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: tuple index out of range

我还能在这里使用格式化功能吗?谢谢...

不要对 SQL 查询使用简单格式;使用 execute 方法的 sql.Identifier for tables, fields and use the 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

这假设您在同一个数据库中有多个模式,因为您不能在 Postgre 中轻松地进行跨数据库查询SQL。