Python 在psycopg2中具有标识符的动态SQL?
嘿,我需要例如“first”。“height”作为“first.height”在选择的部分,但对于所有属性。这就是我能做的。我无法从中取得任何进展。有什么办法吗 最后,sql应该是这样的Python 在psycopg2中具有标识符的动态SQL?,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,嘿,我需要例如“first”。“height”作为“first.height”在选择的部分,但对于所有属性。这就是我能做的。我无法从中取得任何进展。有什么办法吗 最后,sql应该是这样的 int1 = "first" int2 = "second" column1 = ['height', 'test1', 'test2'] column2 = ['height', 'width'] int1_attr = [sql.Identifier(int1,s) for s in column1] i
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" )
您可以使用
Identifier
创建限定的列名:
>> 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\u attr中,您只是用表“.column”
标识列。您需要做的是将int1_attr构建为“table”;“column”构建为“table.column”
。这可以通过以下方式实现:
NAMED_EXPRESSION = '%s as %s'
QUALIFIED_NAME = '%s.%s'
int1_attr = [
NAMED_EXPRESSION % (
sql.Identifier(int1, s),
sql.Identifier(QUALIFIED_NAME % (int1, s))
) for s in column1
]
你教了我很多。但是有了这些,它就不能与sql.sql()一起工作。谢谢,顺便说一句。非常感谢,这很有效!我只是在
sql.composited(int1\u attr)中使用了它。
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
]