我正在从Hibernate中的MySQL表中检索一些密码值,并将其替换为MySQL中的其他字符串。我知道Oracle中有translate()来进行替换,但我在MySQL中找不到任何相同的东西。 除了MySQL中的Replace()还是可以用于相同的任何库之外,还有其他替代解决方案吗?
答案 0 :(得分:5)
您可以这样创建一个:
CREATE FUNCTION `translate`(subject varchar(255), what varchar(255), replace_to varchar(255)) RETURNS varchar(255)
begin
declare c int unsigned default 0;
declare result varchar(255);
set result = subject;
while c <= length(subject) do
set result = replace(result, mid(what, c, 1), mid(replace_to, c, 1) );
set c=c+1;
end while;
return result;
end
然后使用:
mysql> select translate('(123) 1234-1234', '( )-','.,.,');
+---------------------------------------------+
| translate('(123) 1234-1234', '( )-','.,.,') |
+---------------------------------------------+
| .123.,1234,1234 |
+---------------------------------------------+
1 row in set (0.00 sec)
答案 1 :(得分:4)
到目前为止,MySQL中没有Oracle的TRANSLATE()函数。但是,您可以使用嵌套的 REPLACE()函数来获得所需的结果。
添加示例 -
Oracle查询 -
SELECT TRANSLATE('Vikas#Bharti-Infy', '#-', '_.') FROM dual;
Vikas_Bharti.Infy
等效的 MySQL查询将是 -
SELECT REPLACE(REPLACE('Vikas#Bharti-Infy', '#', '_'),'-','.');
Vikas_Bharti.Infy
答案 2 :(得分:0)
我稍微调整了Flavio的答案,以下功能似乎对我有用。
CREATE FUNCTION `translate` (
tar VARCHAR (255),
ori VARCHAR (255),
rpl VARCHAR (255)
) RETURNS VARCHAR (255) CHARSET utf8mb4 DETERMINISTIC BEGIN
DECLARE i INT UNSIGNED DEFAULT 0;
DECLARE cur_char CHAR (1);
DECLARE ori_idx INT UNSIGNED;
DECLARE result VARCHAR (255);
SET result = '';
WHILE i <= length(tar) DO
SET cur_char = mid(tar, i, 1);
SET ori_idx = INSTR(ori, cur_char);
SET result = concat(
result,
REPLACE(
cur_char,
mid(ori, ori_idx, 1),
mid(rpl, ori_idx, 1)
));
SET i = i + 1;
END WHILE;
RETURN result;
END
通过以下示例进行测试:
mysql> SET @map_src = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
Query OK, 0 rows affected (0.00 sec)
mysql> SET @map_des = 'nrgzujmaqbetylxwkdohpfvcisNRGZUJMAQBETYLXWKDOHPFVCIS2014587639';
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT translate('https://456.HELLO.world', @map_src, @map_des) as f1;
+-------------------------+
| f1 |
+-------------------------+
| ahhwo://458.AUTTX.vxdtz |
+-------------------------+
1 row in set (0.00 sec)
答案 3 :(得分:0)
cat file.json | jq '.interface[] | select(.description | contains ("VLL"|"2002089"|"otherstuff" ) | not )'