2012-12-13 60 views
0

我在我的数据库中有这个SQL查询,这导致与heroku上的PostgreSQL有关的问题,导致页面没有在heroku日志中加载上述错误。我使用PostgreSQL 9.1.6所以以前的错误已显然已经固定PGError:错误:列“recipes.id”必须出现在GROUP BY子句中或用于聚合函数

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

我就如何重构这一点,以便将work.Could任何建议,请不确定?

谢谢

回答

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 

你会发现,你只有在选择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之后的其余列。

+0

哦这是简单的,现在我感到很傻,谢谢你虽然 – Richlewis

+0

我接受答案,因为这解决了这个问题,但现在我得到ActionView :: Template :: Error(缺少属性:名称): 任何想法?它关于每个块 – Richlewis

+0

请看更新的答案 – RichardTheKiwi

相关问题