select sum(table_3.col_1) as number,
(CASE
when table_1.line_1 ~* '(?i)City\s*(\d+)' then 'C' || (select (regexp_matches(table_1.line_1, '(?i)City\s*(\d+)'))[1])
when table_1.line_2 ~* '(?i)City\s*(\d+)' then 'C' || (select (regexp_matches(table_1.line_2, '(?i)City\s*(\d+)'))[1])
when table_1.line_3 ~* '(?i)City\s*(\d+)' then 'C' || (select (regexp_matches(table_1.line_3, '(?i)City\s*(\d+)'))[1])
when table_1.line_4 ~* '(?i)City\s*(\d+)' then 'C' || (select (regexp_matches(table_1.line_4, '(?i)City\s*(\d+)'))[1])
when table_1.line_5 ~* '(?i)City\s*(\d+)' then 'C' || (select (regexp_matches(table_1.line_5, '(?i)City\s*(\d+)'))[1])
when table_1.line_6 ~* '(?i)City\s*(\d+)' then 'C' || (select (regexp_matches(table_1.line_6, '(?i)City\s*(\d+)'))[1])
when table_1.line_7 ~* '(?i)City\s*(\d+)' then 'C' || (select (regexp_matches(table_1.line_7, '(?i)City\s*(\d+)'))[1])
when table_1.line_8 ~* '(?i)City\s*(\d+)' then 'C' || (select (regexp_matches(table_1.line_8, '(?i)City\s*(\d+)'))[1])
else 'City'::varchar
end
) as string_result
from table_1
join table_2 on table_1.id = table_2.table_1_id
join table_3 on table_2.id = table_3.table_2_id
join table_4 on table_3.table_4_id = table_4.id
where table_4.id = 2
group by string_result
当我在 pgadmin 中运行上述查询时,我得到了我期望的所有信息。超过 20 行。但是当我使用 heredoc 在 rails 中运行它时,ActiveRecord::Base.connection.execute(sql)
我只返回最后一行。我已经在其他项目中完成了几乎完全相同的事情(当然是不同的数据),并取得了巨大的成功。我不知道为什么在 Rails 中运行时只返回一行
更新:我能够弄清楚为什么会发生这种情况,但仍然有问题纠正它。问题是,当查询传递到ActiveRecord::Base.connection.execute(sql)
它时,它正在逃避我的正则表达式的空间和数字要求。我仍在浏览 postgres 模式匹配文档,但目前我很难使用正则表达式,因为我对使用它们仍然很陌生。但我正在尝试捕获字符串中的数字匹配类似'City 24'
与城市大小写不敏感的匹配的地方
终于开始围绕正则表达式了。我终于能够解决我的问题。这是数字捕获。它在 pgadmin 中工作,(\d+)
但是当通过ActiveRecord::Base.connections.execute(sql)
它时由于某种原因它不起作用。解决方法是给它一个范围,[0-9]
因为+
只是一个或多个我给了它{1,2}
。所以现在正则表达式是(?i)City\s*([0-9]{1,2})
This 将不区分大小写匹配字符串,'City'
后跟任意数量的空格。之后将抓取前两位数字。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句