python - psycopg2 中带有标识符的动态 SQL?

标签 python postgresql psycopg2

int1 = "first"
int2 = "second"
column1 = ['height', 'test1', 'test2']
column2 = ['height', 'width']

int1_attr = [sql.Identifier(int1,s) for s in column1]
int2_attr = [sql.Identifier(int2,s)for s in column2]

qry_str = sql.SQL("CREATE TABLE IF NOT EXISTS {} as (Select {},{}, st_intersection({},{}) from {},{} )").format(
sql.Identifier('Intersection'),
sql.SQL(', ').join(int1_attr),
sql.SQL(', ').join(int2_attr),
sql.Identifier(int1+".geom"),
sql.Identifier(int2+".geom"),
sql.Identifier(int1),
sql.Identifier(int2)
)
print(qry_str.as_string(con))

>> CREATE TABLE IF NOT EXISTS "Intersection" as (Select "first"."height", "first"."test1", "first"."test2","second"."height", "second"."width", st_intersection("first.geom","second.geom") from "first","second" )

嘿,我需要例如“first”,“height”作为选择部分的“first.height”,但对于所有属性。该代码是我能做的。我无法从中取得任何进展。有什么办法吗?

最后的sql应该是这样的;

>> CREATE TABLE IF NOT EXISTS "Intersection" as (Select "first"."height" as "first.height", "first"."test1" as "first.test1", "first"."test2" as "first.test2" ,"second"."height" as "second.height", "second"."width" as "second.with", st_intersection("first.geom","second.geom") from "first","second")

最佳答案

int1_attr 中,您只是用 "table"."column" 标识列。您需要做的是将 int1_attr 构建为 "table"."column"AS "table.column"。这可以使用:

int1_attr = [
    sql.SQL("{} AS {}").format(
        sql.Identifier(int1, s),
        sql.Identifier("{}.{}".format(int1, s))
    ) for s in column1
]
int2_attr = [
    sql.SQL("{} AS {}").format(
        sql.Identifier(int2, s),
        sql.Identifier("{}.{}".format(int2, s))
    ) for s in column2
]

关于python - psycopg2 中带有标识符的动态 SQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58596651/

相关文章:

python - Web 通知推送在 Chrome 上从 python 抛出 400

python - Tkinter:标签和按钮框架之间的空间太大

python - 在 seaborn 散点图中显示相关值

postgresql - 在 PostgreSQL 中使用继承

python - 在守护进程中失去与 postgresql 的连接

python - Matplotlib 中许多子图的通用标题

sql - 为 Postgresql 准备 SQL 计划 - 带有绑定(bind)变量列表

mysql - 将 MySQL CREATE TABLE 语法转换为 Postgresql

python - 通过 psycopg2 获取警告信息

python - psycopg2.errors.InFailedSqlTransaction : current transaction is aborted, 命令被忽略,直到事务 block 结束