MYSql 多重替换查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5460364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MYSql multiple replace query
提问by jamjam
I have this
我有这个
UPDATE table
SET example = REPLACE(example, '1', 'test')
WHERE example REGEXP '1$'
So this code replaces all instances of "1" in the "example" field with "test".
因此,此代码将“示例”字段中“1”的所有实例替换为“测试”。
I want to repeat this for 2, 3, 4 and so on.
我想对 2、3、4 等重复此操作。
But it would be very inefficient to use separate querys.
但是使用单独的查询会非常低效。
Is the any way I can do this with just one query?
我可以通过一个查询来做到这一点吗?
Thanks
谢谢
回答by zerkms
Matryoshka-way ;-)
套娃方式 ;-)
REPLACE(REPLACE(REPLACE(example, '3', 'test') , '2', 'test') , '1', 'test')
回答by Konchog
A stored procedure.
一个存储过程。
Given you have a table 'lut' with a set of values that you want replacing in a field 'content' from a table is called 'example'
假设您有一个表 'lut',其中包含一组要在表中的字段 'content' 中替换的值,称为 'example'
delimiter //
CREATE PROCEDURE myreplace()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE lv CHAR(64);
DECLARE li INT;
DECLARE lut CURSOR FOR SELECT id,value FROM lut l;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN lut;
lut_loop: LOOP
FETCH lut INTO li,lv;
IF done THEN
LEAVE lut_loop;
END IF;
update example set content = replace(content,lv,li);
END LOOP;
CLOSE lut;
END;
//
delimiter ;
call myreplace();
drop procedure myreplace;