我有两个模型类:Class A
代表table_a
,Class 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