Nested query in squeel

佐手、 提交于 2019-12-05 18:38:18

I wouldn't know about Squeel, but the error you see could be fixed by upgrading PostgreSQL.

Some RDBMSs are happy with this, but postgres complains:

ERROR: column "users.name" must appear in the GROUP BY clause or be used in an aggregate function

Starting with PostgreSQL 9.1, once you list a primary key in the GROUP BY you can skip additional columns for this table and still use them in the SELECT list. The release notes for version 9.1 tell us:

Allow non-GROUP BY columns in the query target list when the primary key is specified in the GROUP BY clause


BTW, your alternative query can be simplified, an additional DISTINCT would be redundant.

SELECT o.*, c.my_count
FROM   onetable o
JOIN (
  SELECT one_id, count(*) AS my_count
  FROM   anothertable
  GROUP  BY one_id
) c ON o.id = counts.one_id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!