请假设this data model。这是我真正拥有的简化模型,但所有重要的领域都在那里。数据库: Postgres 。我想计算这些模型的一些统计数据,我偶然发现了这个问题:
c = Customer.select().random(1)[0] # example
query = left_join(
(
p,
count(i.order.customer == c),
count((b.is_used == True) for b in i.bonuses),
count(i)
) for p in Product
for i in p.order_items)
现在尝试显示结果(实际上我对聚合做了一些过滤)
query.show()
得出这个:
ProgrammingError: subquery uses ungrouped column "i.id" from outer query
LINE 4: WHERE "i"."id" = "b"."order_item"
我该怎么做才能纠正这个问题?
生成的SQL如下所示:
SELECT "p"."id", COUNT(case when "order"."customer" = ? then 1 else null end), (
SELECT COUNT(DISTINCT "b"."is_used" = 1)
FROM "Bonus" "b"
WHERE "i"."id" = "b"."order_item"
), COUNT(DISTINCT "i"."id")
FROM "Product" "p"
LEFT JOIN "OrderItem" "i"
ON "p"."id" = "i"."product"
LEFT JOIN "Order" "order"
ON "i"."order" = "order"."id"
GROUP BY "p"."id"
编辑:
我的真实模型是为了适应Django使用的数据库,所以每个类都有_table_
,所有外键都有column=something_id
。但除此之外,一切看起来都不错,我可以轻松地进行任何简单的查询。
答案 0 :(得分:0)
看来我需要将代码改写为此格式:
query = left_join(
(
p,
count(i.order.customer == c),
count(b.is_used == True),
count(i)
) for p in Product
for i in p.order_items
for b in i.bonuses)