我有两个表:
table1
-----------------
| id | salary |
| 1 | 2500 |
| 2 | 500 |
-----------------
table2
-------------------------------
| id | outlay | table1_fk |
| 1 | 20 | 1 |
| 2 | 40 | 1 |
| 3 | 1000 | 2 |
-------------------------------
我需要从table1 +工资总和大于工资总和的费用总和中选择所有行 MySQL查询将是:
SELECT t1.*, COALESCE(SUM(t2.outlay),0) AS total_outlay
FROM table1 AS t1
LEFT JOIN table2 AS t2 ON t1.id = t2.table1_fk
GROUP BY t1.id
HAVING total_outlay < t1.salary;
Django ORM是否可能?到目前为止,我有这个:
Model1.objects.filter(somefilterlogic).annotate(outlay_total=Sum("model2__outlay"))
You can
.filter(…)
[Django-oc] after the.annotate(…)
[Django-doc] clause: