如何在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 

只要我知道,Rails中没有group_concat等价物,但你可以使用includes来做到这一点:

 continents = Continents .joins(:countries, :event_locations) .includes(:countries) .group("continents.code") continents.each do |continent| continent.countries.join(",") end 

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

 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,’,’)
  • Oracle :listagg(countries.name,’,’)
Interesting Posts