PGError:错误:列“recipes.id”必须出现在GROUP BY子句中或用于聚合函数

时间:2012-12-13 22:25:32

标签: sql ruby-on-rails-3 postgresql heroku

我在我的数据库中有这个SQL查询,导致heroku上的PostgreSQL出现问题,导致页面无法在heroku日志中加载上述错误。我正在使用postgreSQL 9.1.6,因此以前的错误显然已得到修复

def self.top_countries
joins(:recipes).
  select('countries.*, count(*) AS recipes_count').
  group('countries.id').
  order('recipes_count DESC')

我不确定如何对其进行重构以使其有效。有人可以提出建议吗?

谢谢

1 个答案:

答案 0 :(得分:1)

def self.top_countries
joins(:recipes).
  select('countries.id, count(*) AS recipes_count').
  group('countries.id').
  order('recipes_count DESC')

这会生成SQL

select countries.id, count(*) AS recipes_count
  from countries
  join recipes on countries.id = recipes.country_id
 group by countries.id
 order by recipes_count

您会注意到SELECT中只有2列 不是Heroku专家,我怀疑你可以通过明确列出你需要的所有国家列,并按完整的列列表分组来实现它。

def self.top_countries
joins(:recipes).
  select('countries.id, countries.name, countries.other, count(*) AS recipes_count').
  group('countries.id, countries.name, countries.other').
  order('recipes_count DESC')

可能有一种更简洁的方式将原始答案(顶部)与top_countries上的countries.id的另一个联接加入group by之后的其余列。< / p>