Oracle
 sql >> Datenbank >  >> RDS >> Oracle

Wie kann ich GROUP_CONCAT in Rails verwenden?

So lange ich weiß, gibt es kein group_concat Äquivalent in Rails, aber Sie können includes verwenden dazu:

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

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

Dies wird nur 2 Abfragen erzeugen - ich weiß, ist nicht so gut wie eine, aber ich denke, das ist das Beste, was Rails ohne "group_concat" tun kann. Der andere Weg wird in etwa so aussehen:

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

Aber wenn Sie das tun, müssen Sie entsprechend Ihrem Datenbankanbieter wechseln.

  • MySQL :group_concat(Länder.Name)
  • PostgreSQL :string_agg(länder.name, ',')
  • Oracle :listagg(länder.name, ',')