How can I use GROUP_CONCAT in Rails?

半腔热情 提交于 2019-11-29 20:59:44

问题


I have the following query which I want to use with ActiveRecord so that it can be translated in native ORACLE based query on production server. Right now I am using 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

回答1:


As long as I know, there's no group_concat equivalent in Rails, but you can use includes to do that:

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

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

This will produce only 2 queries - I know, is not so good as one, but I think that is the best than Rails can do without "group_concat". The other way will be something like that:

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

But if you do that, you need to change according to your database vendor.

  • MySQL: group_concat(countries.name)
  • PostgreSQL: string_agg(countries.name, ',')
  • Oracle: listagg(countries.name, ',')


来源:https://stackoverflow.com/questions/28146848/how-can-i-use-group-concat-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!