如何在Rails中使用GROUP_CONCAT?

Vol*_*il3 6 sql oracle ruby-on-rails group-concat

我有以下查询,我想与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
Run Code Online (Sandbox Code Playgroud)

Dan*_*iro 14

只要我知道,group_concat在Rails中没有等效的东西,但你可以用它includes来做到这一点:

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

continents.each do |continent| 
  continent.countries.join(",")
end
Run Code Online (Sandbox Code Playgroud)

这将只产生2个查询 - 我知道,它不如一个查询,但我认为这比Rails没有"group_concat"更好.另一种方式是这样的:

Country
  .select("countries.id, GROUP_CONCAT(countries.name)as grouped_name")
  .joins(:continents, :event_locations)
  .group("continents.code")
Run Code Online (Sandbox Code Playgroud)

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

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

  • 是的,并在运行中找出驱动程序并使用apt查询.我很惊讶为什么它不受支持. (2认同)