【问题标题】:How can I use GROUP_CONCAT in Rails?如何在 Rails 中使用 GROUP_CONCAT?
【发布时间】:2015-03-24 16:08:53
【问题描述】:

我有以下查询,我想将它与 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

【问题讨论】:

  • 这根本不是一个重复的问题。 OP 希望使用 Rails 做同样的事情。 投票重新打开它。
  • @Ben 不重复。我在里面清楚地提到了 Rails
  • 您想要一个与 SQLite 相同的 Oracle 查询吗?或者,你希望有人给你写一大堆做同样事情的 RoR 代码?第一个是重复的;第二个我同意不会。
  • 我稍后再说。我知道哪些方法在 SQLite 和 Oracle 中提供了类似的功能

标签: sql ruby-on-rails oracle group-concat


【解决方案1】:

据我所知,Rails 中没有 group_concat 等效项,但您可以使用 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, ',')
  • Oracle:listagg(countries.name, ',')

【讨论】:

  • 是的,在运行时找出驱动程序并使用 apt 查询。我很惊讶为什么不支持它。
【解决方案2】:

在 Rails 6 上(我不知道其他人),如果你使用 select,你可以只生成一个查询

continents = Continent.joins(:country).select(:name, 'countries.name as country_name')

countries_list = []

continents.each do |continent|
  countries_list << continent.country_name
end

我知道代码没有按大陆分组,但我的想法是显示how to make the query at oncehow to access the result。如何以更适合自己的方式进行分组。

记住你需要在 Continent 类中创建关系

has_many :country

希望我能帮助别人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    • 2012-11-07
    • 1970-01-01
    相关资源
    最近更新 更多