如何使用 SQLAlchemy 进行批量“SELECT”查询?
How to make bulk `SELECT` queries with SQLAlchemy?
我有一个简单的查询:
query = """SELECT (A.name, A.food) FROM animals AS A
WHERE
A.type = :animal_type AND M.id = :member_id
INNER JOIN members as M ON M.animal_id = A.animal_id;"""
我有一个输入列表,例如:
animals_memberships = [
{
"animal_type": "BEAR",
"member_id": 100,
},
{
"animal_type": "RAT",
"member_id": 200,
},
...
]
目前,我正在遍历每个动物成员并查询数据:
queries = []
for item in animals_memberships:
session.execute(
query, {
"member_id": item["member_id"],
"animal_type": item["animal_type"],
}
)
animal_names_foods = [
result.fetchall()[0] for result in queries
]
是否可以执行“批量”查询,类似于批量插入如何使用 session.bulk_save_objects()
?
您可以像这样在一次查询中获取所有数据
SELECT (A.name, A.food) FROM animals AS A
WHERE
(A.type, M.id) in (VALUES ('BEAR', 100), ('RAT', 200))
INNER JOIN members as M ON M.animal_id = A.animal_id;
顺便问一下,如何在 python
中以安全的方式构建此查询
animals_memberships = [
{
"member_id": 100,
"animal_type": "BEAR",
},
{
"member_id": 200,
"animal_type": "RAT",
},
]
parts = []
params = {}
for idx, item in enumerate(animals_memberships):
params[f"member_id_{idx}"] = item["member_id"]
params[f"animal_type_{idx}"] = item["animal_type"]
parts.append(f"(:member_id_{idx}, :animal_type_{idx})")
parts_str = ",".join(parts)
query = f"""
SELECT (A.name, A.food) FROM animals AS A
WHERE
(A.type, M.id) IN (VALUES {parts_str})
INNER JOIN members as M ON M.animal_id = A.animal_id;
"""
session.execute(query, params)
我有一个简单的查询:
query = """SELECT (A.name, A.food) FROM animals AS A
WHERE
A.type = :animal_type AND M.id = :member_id
INNER JOIN members as M ON M.animal_id = A.animal_id;"""
我有一个输入列表,例如:
animals_memberships = [
{
"animal_type": "BEAR",
"member_id": 100,
},
{
"animal_type": "RAT",
"member_id": 200,
},
...
]
目前,我正在遍历每个动物成员并查询数据:
queries = []
for item in animals_memberships:
session.execute(
query, {
"member_id": item["member_id"],
"animal_type": item["animal_type"],
}
)
animal_names_foods = [
result.fetchall()[0] for result in queries
]
是否可以执行“批量”查询,类似于批量插入如何使用 session.bulk_save_objects()
?
您可以像这样在一次查询中获取所有数据
SELECT (A.name, A.food) FROM animals AS A
WHERE
(A.type, M.id) in (VALUES ('BEAR', 100), ('RAT', 200))
INNER JOIN members as M ON M.animal_id = A.animal_id;
顺便问一下,如何在 python
中以安全的方式构建此查询animals_memberships = [
{
"member_id": 100,
"animal_type": "BEAR",
},
{
"member_id": 200,
"animal_type": "RAT",
},
]
parts = []
params = {}
for idx, item in enumerate(animals_memberships):
params[f"member_id_{idx}"] = item["member_id"]
params[f"animal_type_{idx}"] = item["animal_type"]
parts.append(f"(:member_id_{idx}, :animal_type_{idx})")
parts_str = ",".join(parts)
query = f"""
SELECT (A.name, A.food) FROM animals AS A
WHERE
(A.type, M.id) IN (VALUES {parts_str})
INNER JOIN members as M ON M.animal_id = A.animal_id;
"""
session.execute(query, params)