SQLAlchemy:一个 "all-inclusive" in_
SQLAlchemy: An "all-inclusive" in_
在通常的 Customer -> Orders 示例模式中,如果我们想要获得所有下订单的客户 order_category_id 设置为 12 或 13,我们会告诉 SQLAlchemy。 ..
for customer in db.query(Customer)\
.join(Order, Customer.id = Order.cst_id)\
.filter(Order.order_category_id.in_([12,13]):
# do something with customer
...
但是,如果我们想要获得所有 Customer
s,这使得 Order
s 具有 12 和 13 order_category_id
秒?在 SQL 中,我将其写为:
select *
from Customer
where
exists (select 1 from Order
where Customer.id = Order.cst_id and Order.order_category_id = 12)
and exists (select 1 from Order
where Customer.id = Order.cst_id and Order.order_category_id = 13)
如何触发 SQLAlchemy 生成此类查询?即与 12 和 13 的订单行关联的一个返回客户实体 category_ids?
像这样:
subq1 = (
Customer.query
.join(Order, Customer.id = Order.cst_id)
.filter(Order.order_category_id == 12)
).subquery()
final_query = (
query(subq1)
.join(Order, Customer.id = Order.cst_id)
.filter(Order.order_category_id == 13)
)
我还没有测试过这个,但我认为它应该可以。
在通常的 Customer -> Orders 示例模式中,如果我们想要获得所有下订单的客户 order_category_id 设置为 12 或 13,我们会告诉 SQLAlchemy。 ..
for customer in db.query(Customer)\
.join(Order, Customer.id = Order.cst_id)\
.filter(Order.order_category_id.in_([12,13]):
# do something with customer
...
但是,如果我们想要获得所有 Customer
s,这使得 Order
s 具有 12 和 13 order_category_id
秒?在 SQL 中,我将其写为:
select *
from Customer
where
exists (select 1 from Order
where Customer.id = Order.cst_id and Order.order_category_id = 12)
and exists (select 1 from Order
where Customer.id = Order.cst_id and Order.order_category_id = 13)
如何触发 SQLAlchemy 生成此类查询?即与 12 和 13 的订单行关联的一个返回客户实体 category_ids?
像这样:
subq1 = (
Customer.query
.join(Order, Customer.id = Order.cst_id)
.filter(Order.order_category_id == 12)
).subquery()
final_query = (
query(subq1)
.join(Order, Customer.id = Order.cst_id)
.filter(Order.order_category_id == 13)
)
我还没有测试过这个,但我认为它应该可以。