简体   繁体   中英

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').

The closest I've come to atm is to nest the replace calls within each other like so

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. 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() :

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

sql fiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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