我有以下查询,我想将其与 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
据我所知,没有group_concat
Rails 中的等效项,但您可以使用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(国家.名称)
-
PostgreSQL:
string_agg(国家.名称, ',')
-
Oracle: listagg(国家.名称, ',')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)