使用 psycopg2 执行多组参数查询
Execute a query for multiple sets of parameters with psycopg2
我有一个 table 我想查询,但我想进行许多特定的查询和 return 一个 table 满足条件的任何结果,并忽略不存在的查询。
data = (
(1, '2020-11-19'),
(1, '2020-11-20'),
(1, '2020-11-21'),
(2, '2020-11-19'),
(2, '2020-11-20'),
(2, '2020-11-21')
)
string = """
SELECT * FROM my_schema.my_table
WHERE my_schema.my_table.song_id = %s
AND my_schema.my_table.date = %s;
"""
execute_values(cursor, string, data)
results = cursor.fetchall()
希望这说明了我在这里想要实现的目标...
我想执行一系列 select 语句,每个语句都有一对参数。如果那对参数在数据库中,则将其附加到结果 table.
唯一的方法是在 for-loop
中手动执行此操作吗?
在循环中执行许多查询不是一个好主意。使用通用的 table 表达式将多对参数传递给单个查询并获得所有参数的结果,例如 this Postgres example.
Python代码:
data = (
(1, '2020-11-19'),
(1, '2020-11-20'),
(1, '2020-11-21'),
(2, '2020-11-19'),
(2, '2020-11-20'),
(2, '2020-11-21')
)
query = """
with data(song_id, date) as (
values %s
)
select t.*
from my_table t
join data d
on t.song_id = d.song_id and t.date = d.date::date
"""
execute_values(cursor, query, data)
results = cursor.fetchall()
我有一个 table 我想查询,但我想进行许多特定的查询和 return 一个 table 满足条件的任何结果,并忽略不存在的查询。
data = (
(1, '2020-11-19'),
(1, '2020-11-20'),
(1, '2020-11-21'),
(2, '2020-11-19'),
(2, '2020-11-20'),
(2, '2020-11-21')
)
string = """
SELECT * FROM my_schema.my_table
WHERE my_schema.my_table.song_id = %s
AND my_schema.my_table.date = %s;
"""
execute_values(cursor, string, data)
results = cursor.fetchall()
希望这说明了我在这里想要实现的目标...
我想执行一系列 select 语句,每个语句都有一对参数。如果那对参数在数据库中,则将其附加到结果 table.
唯一的方法是在 for-loop
中手动执行此操作吗?
在循环中执行许多查询不是一个好主意。使用通用的 table 表达式将多对参数传递给单个查询并获得所有参数的结果,例如 this Postgres example.
Python代码:
data = (
(1, '2020-11-19'),
(1, '2020-11-20'),
(1, '2020-11-21'),
(2, '2020-11-19'),
(2, '2020-11-20'),
(2, '2020-11-21')
)
query = """
with data(song_id, date) as (
values %s
)
select t.*
from my_table t
join data d
on t.song_id = d.song_id and t.date = d.date::date
"""
execute_values(cursor, query, data)
results = cursor.fetchall()