我有这样的SQL查询(我知道这种情况可以优化,我的意思是使用具有相同参数的不同查询):
select * from a where x > %s and y < %s
union
select * from b where x > %s and y < %s
union
select * from c where x > %s and y < %s
union
select * from d where x > %s and y < %s
然后我使用psycopg2 execute来填充参数:
mycursor.execute(query_from_above, (since, to, since, to, since, to, since, to))
我想这样称呼
mycursor.execute(query_from_above, (since, to))
是否可以以某种方式修改查询,以便可以使用较短版本的execute()?
编辑: 有解决此问题的方法:http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries 也许是更好的选择:http://initd.org/psycopg/docs/sql.html
答案 0 :(得分:2)
mycursor.execute("""select * from a where x > %(since)s and y < %(to)s
union
select * from b where x > %(since)s and y < %(to)s
union
select * from c where x > %(since)s and y < %(to)s
union
select * from d where x > %(since)s and y < %(to)s""",
{'since': since, 'to': to}
)
可以尝试这样的事情吗?