0

我的数据库中有这个 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')

结尾

我不确定如何重构它以使其正常工作。有人可以建议吗?

谢谢你

4

1 回答 1

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_countriesoncountries.id以获取group by.

于 2012-12-13T22:27:13.847 回答