简单查询
这可以是简单得多与 PostgreSQL9.1 或更高版本。正如这个密切相关的答案中所解释的:
- PGError:错误:对象及其 has_many 对象的 AR 查询的 WHERE 子句中不允许聚合 https://stackoverflow.com/questions/8684486/rails-3-getting-a-pgerror-error-aggregates-not-allowed-in-where-clause-on-a-a/8684512#8684512
就足够了GROUP BY
the 首要的关键一张桌子的。自从:
foo1 是主键
..您可以将示例简化为:
SELECT foo1, foo2, foo3, foo4, foo5, foo6, string_agg(aggregated_field, ', ')
FROM tbl1
GROUP BY 1
ORDER BY foo7, foo8; -- have to be spelled out, since not in select list!
多表查询
但是,由于您有:
更多字段和 LEFT JOIN,重要的是所有这些字段都具有 1 到 1 或 1 到 0 关系,除了一个我想要聚合的 1 到 n 字段
..应该更快更简单先聚合,后加入:
SELECT t1.foo1, t1.foo2, ...
, t2.bar1, t2.bar2, ...
, a.aggregated_col
FROM tbl1 t1
LEFT JOIN tbl2 t2 ON ...
...
LEFT JOIN (
SELECT some_id, string_agg(agg_col, ', ') AS aggregated_col
FROM agg_tbl a ON ...
GROUP BY some_id
) a ON a.some_id = ?.some_id
ORDER BY ...
这样,查询的大部分就根本不需要聚合。
我最近在 SQL Fiddle 中提供了一个测试用例来证明这个相关答案中的观点:
- PostgreSQL - 按数组排序 https://stackoverflow.com/questions/15664373/postgresql-order-by-an-array/15674585#15674585
既然你指的是这个相关答案 https://stackoverflow.com/a/1777448/1331430: No, DISTINCT
在这种情况下根本没有帮助。