如何在Rails中使用GROUP_CONCAT?

挥发物3

我有以下查询,希望与ActiveRecord一起使用,以便可以在生产服务器上基于本机ORACLE的查询中翻译该查询。现在我正在使用SQLITe。

select c.name,co.code,GROUP_CONCAT(c.name) AS GroupedName
from countries c
INNER JOIN continents co
on c.continent_code = co.code
INNER JOIN event_locations el
on el.location_id = c.id
group by co.code
丹尼尔·洛雷罗(Daniel Loureiro)

据我所知,group_concatRails中没有等效项,但是您可以使用它includes来实现:

continents = Continents
  .joins(:countries, :event_locations)
  .includes(:countries)
  .group("continents.code")

continents.each do |continent| 
  continent.countries.join(",")
end

这只会产生2个查询-我知道,这不如一个查询好,但我认为这是Rails在没有“ group_concat”的情况下所能做到的最好的查询。另一种方法是这样的:

Country
  .select("countries.id, GROUP_CONCAT(countries.name)as grouped_name")
  .joins(:continents, :event_locations)
  .group("continents.code")

但是,如果这样做,则需要根据数据库供应商进行更改。

  • MySQL的:group_concat(countries.name)
  • PostgreSQL:string_agg(countries.name,',')
  • 甲骨文:listagg(countries.name,',')

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章