TRANSLATE 函数
对于给定表达式,将指定字符的所有匹配项替换为指定替代项。现有字符将按其在 characters_to_replace 和 characters_to_substitute 参数中的位置映射到替换字符。如果在 characters_to_replace 参数中指定的字符多于在 characters_to_substitute 参数中指定的字符,返回值中将省略 characters_to_replace 参数中的额外字符。
TRANSLATE 与 REPLACE 函数 和 REGEXP_REPLACE 函数 相似,只不过 REPLACE 将整个字符串替换为其他字符串,REGEXP_REPLACE 可让您在字符串中搜索正则表达式模式,而 TRANSLATE 进行多次单字符替换。
如果任何参数为 null,则返回
NULL
。
TRANSLATE( expression, characters_to_replace, characters_to_substitute )
要将列中所有值的 at(@)符号替换为句点,请使用以下示例。
SELECT email, TRANSLATE(email, '@', '.') as obfuscated_email FROM users LIMIT 10;
+---------------------------------------+---------------------------------------+ | email | obfuscated_email | +---------------------------------------+---------------------------------------+ | [email protected] | Cum.accumsan.com | | [email protected] | lorem.ipsum.Vestibulumante.com | | [email protected] | non.justo.Proin.ametconsectetuer.edu | | [email protected] | non.ante.bibendum.porttitortellus.org | | [email protected] | eros.blanditatnisi.org | | [email protected] | augue.Donec.ca | | [email protected] | cursus.pedeacurna.edu | | [email protected] | at.Duis.com | | [email protected] | quam.facilisisvitaeorci.ca | | [email protected] | mi.lorem.nunc.edu | +---------------------------------------+---------------------------------------+
要将空格替换为下划线并去掉列中所有值的句点,请使用以下示例。
SELECT city, TRANSLATE(city, ' .', '_') FROM users WHERE city LIKE 'Sain%' OR city LIKE 'St%' GROUP BY city ORDER BY city;
+----------------+---------------+ | city | translate | +----------------+---------------+ | Saint Albans | Saint_Albans | | Saint Cloud | Saint_Cloud | | Saint Joseph | Saint_Joseph | | Saint Louis | Saint_Louis | | Saint Paul | Saint_Paul | | St. George | St_George | | St. Marys | St_Marys | | St. Petersburg | St_Petersburg | | Stafford | Stafford | | Stamford | Stamford | | Stanton | Stanton | | Starkville | Starkville | | Statesboro | Statesboro | | Staunton | Staunton | | Steubenville | Steubenville |