简体   繁体   English

如何替换 PostgreSQL 中一列文本中的字符数组?

[英]How to replace an array of characters in a column of text in PostgreSQL?

I have 2 text columns where I need to replace (on update) chars from array 1 ('q','x','y','z') to their index-equivalent value in array 2 ('a','b','c','d').我有 2 个文本列,我需要将数组 1('q'、'x'、'y'、'z')中的(更新时)字符替换为它们在数组 2 中的索引等效值('a'、' b','c','d')。

The closest I've come to atm is to nest the replace calls within each other like so我最接近 atm 的是将替换调用嵌套在彼此中,就像这样

UPDATE 
    mytable 
SET 
    col1=replace(
            replace(
                replace(
                    replace(
                        col1,'q','a'
                    ),'x','b'
                ),'y','c'
            ),'z','d'
        ),
    col2=replace(
            replace(
                replace(
                    replace(
                        col2,'q','a'
                    ),'x','b'
                ),'y','c'
            ),'z','d'
        )        

but surely there must be a better way to do this?但肯定必须有更好的方法来做到这一点? In my live case I have 14 of those char pairs.在我的现场案例中,我有 14 个字符对。 If it has any relevance - the chars are a mix of japanese hieroglyphs and accented letters from Swedish alphabet.如果它有任何相关性 - 这些字符是日本象形文字和瑞典字母表中带重音字母的混合体。

PostgreSQL have special function for this, translate() : PostgreSQL 对此有特殊功能, translate()

update mytable set
    col1 = translate(col1, 'qxyz', 'abcd'),
    col2 = translate(col2, 'qxyz', 'abcd')

sql fiddle example sql小提琴示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM