String PostgreSQL中的多个字符串替换
我有一列用空格分隔的缩写词,如下所示String PostgreSQL中的多个字符串替换,string,postgresql,replace,String,Postgresql,Replace,我有一列用空格分隔的缩写词,如下所示 'BG MSG' 另外,还有另一张表,上面有替换项 target replacement ---------------------- 'BG', 'Brick Galvan' 'MSG', 'Mosaic Galvan' 目标是对缩写应用所有替换,以获得类似 'Brick Galvan Mosaic Galvan'来自'BG MSG' 我知道我能做到 replace(replace('BG MSG','BG','Brick Galvan'),'MSG
'BG MSG'
另外,还有另一张表,上面有替换项
target replacement
----------------------
'BG', 'Brick Galvan'
'MSG', 'Mosaic Galvan'
目标是对缩写应用所有替换,以获得类似
'Brick Galvan Mosaic Galvan'
来自'BG MSG'
我知道我能做到
replace(replace('BG MSG','BG','Brick Galvan'),'MSG','Mosaic Galvan')
但是想象一下有成百上千的替代品,它们可以从一天换到下一天。结果查询将难以维护
我的意思是,我可以做一个代码生成器来创建包含所有嵌套替换的查询,但我正在寻找更优雅和postgres原生的东西
我已经找到了这样的解决方案
但它们似乎只对单个字符有效。嵌套替换方法也可以,但它非常难看,对吗
SELECT REPLACE(REPLACE(REPLACE(REPLACE(…
在仔细格式化以使其看起来可读之后,您可以获得以下最佳结果:
SELECT
REPLACE(
REPLACE(
REPLACE(
REPLACE(...
另一方面,您可以只使用横向联接
解决方案,该解决方案使用更多字符,但它肯定更具可读性
-- Input: BG, MSG
-- Output: Brick Galvan, Mosaic Galvan
SELECT msg.Materials
FROM (SELECT 'BG, MSG' AS Materials) mt
INNER JOIN LATERAL (SELECT REPLACE(mt.Materials::text, 'BG', 'Brick Galvan') AS Materials) bg ON true
INNER JOIN LATERAL (SELECT REPLACE(bg.Materials::text, 'MSG', 'Mosaic Galvan') AS Materials) msg ON true;
假设您的桌子如下所示:
create table my_table(id serial primary key, abbrevs text);
insert into my_table (abbrevs) values
('BG MSG');
create table substitutions(target text, replacement text);
insert into substitutions values
('BG', 'Brick Galvan'),
('MSG', 'Mosaic Galvan');
您可以在一行中获取每个缩写:
select id, unnest(string_to_array(abbrevs, ' ')) as abbrev
from my_table
id | abbrev
----+--------
1 | BG
1 | MSG
(2 rows)
并使用它们加入substitution
表并获取全名:
select id, string_agg(replacement, ' ') as full_names
from (
select id, unnest(string_to_array(abbrevs, ' ')) as abbrev
from my_table
) t
join substitutions on abbrev = target
group by id
id | full_names
----+----------------------------
1 | Brick Galvan Mosaic Galvan
(1 row)
我想您可以使用自定义聚合,或PL/PGSQL函数中的某个循环。乍一看,这似乎是您的解决方案—这正是我要寻找的。谢谢将检查并可能接受答案。检查您的解决方案,效果很好。这真的是一种后进生做事的方式。每当您需要做一些复杂的事情时,您应该考虑在任务更简单的地方构建中间表。至少对我来说是这样。再次感谢克林。我很高兴能帮上忙,萨鲁多斯!