我有三张表之间的关系;
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;
我看到另一个问题here,我怀疑这可能是解决我的问题的方法,但我无法理解为多种关系工作的答案。
答案 0 :(得分: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]