2

我有三个表之间的关系;

Customer --> Order --> OrderLine

我想知道哪些客户下订单的订单行最多。使用纯 SQL,我将继续使用以下查询;

SELECT a.*, COUNT( c.id ) AS total FROM customer AS a
 LEFT JOIN order AS b ON a.id = b.customer_id
 LEFT JOIN order_line AS c ON b.id = c.order_id
 GROUP BY a.id ORDER BY total DESC;

我在这里看到了另一个问题,我怀疑这可能是我的问题的解决方案,但我无法真正理解处理多个关系的答案。

4

1 回答 1

0

这将为您提供每位客户的最大订单行数:

from django.db.models import Max
custs = Customer.objects.annotate(max_order_lines=Max(order__orderline)).values('id', 'max_order_lines').order_by('-max_order_lines')
max_cust = custs[0]
于 2013-07-27T05:21:03.600 回答