Django使用额外的连接聚合/注释

时间:2017-04-07 17:23:29

标签: django django-models

我有两个模型类:Class A代表table_aClass B代表table_b。有没有办法聚合或注释Class A以包含Class B中除聚合列之外的字段的值?

可以完成我需要的SQL查询如下:

SELECT
  a.*,
  b2.col2
FROM table_a AS a
  LEFT JOIN (SELECT
               max(col1) AS m,
               a_id
             FROM table_b
             GROUP BY a_id) AS b1 ON b1.a_id = a.id
  LEFT JOIN table_b AS b2 ON b1.a_id = b2.a_id AND b2.col1 = b1.m

但是聚合函数只返回使用它检索的数据:

SELECT
  a.*,
  b1.m
FROM table_a AS a
  LEFT JOIN (SELECT
               max(col1) AS m,
               a_id
             FROM table_b
             GROUP BY a_id) AS b1 ON b1.a_id = a.id

0 个答案:

没有答案