是否有可能在MySQL中搜索和替换字符串数组?

时间:2012-04-17 17:08:05

标签: mysql sql

考虑以下数组:

"Bank of America"    => "BOA",
"Microsoft"          => "MSFT",
"Berkshire Hathaway" => "BRK"

实际上,阵列长100对。如果我有一个带有文本记录的MySQL表“字符串”:

str_id  str_text
-------------------------------------------------------------
1       I wish I had bought Berkshire Hathaway in the 1980's!
2       Microsoft to release Windows 8 in 4 flavours

有没有办法 - 在SQL中! - 遍历所有数百万条记录并用其代码替换所有公司名称?那么当查询完成后,字符串表将如下所示?

str_id  str_text
-------------------------------------------------------------
1       I wish I had bought BRK in the 1980's!
2       MSFT to release Windows 8 in 4 flavours

我问,因为它可以使用PHP,但这本身就会变慢,因为我必须检索几千条记录,循环遍历它们,更新它们,使用crontab检索数千个等等。 / p>

2 个答案:

答案 0 :(得分:2)

没有PHP的替代方案(仅限MySQL):

创建MySQL程序:

    DELIMITER // 
    DROP PROCEDURE IF EXISTS replace_strings// 
    CREATE PROCEDURE replace_strings(IN table_name VARCHAR(100), IN field_name VARCHAR(100))

    BEGIN

    DECLARE done INT DEFAULT FALSE;
    DECLARE str_from VARCHAR(255);
    DECLARE str_to VARCHAR(255);
    DECLARE cur1 CURSOR FOR SELECT string_from, string_to FROM replacements;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    OPEN cur1;

    read_loop: LOOP
        FETCH cur1 INTO str_from, str_to;
        IF done THEN
            LEAVE read_loop;
        END IF;

    SET @sql_command = CONCAT("UPDATE ",table_name," SET ",field_name," = REPLACE(",field_name,", '",str_from,"', '",str_to,"')");
    PREPARE stmt FROM @sql_command;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    END LOOP;

    CLOSE cur1;

    END // 
    DELIMITER ;

使用字段replacementsstring_from创建表格string_to。添加可能的自动更改到此表。

在代码中使用过程调用:

    CALL replace_strings('strings','str_text');

答案 1 :(得分:1)

为什么不使用REPLACE功能?

update 
  mytable 
set 
  str_text=replace(str_text, 'Bank of America', 'BOA');

所以你应该遍历你的数组并执行那个sql请求:

foreach ($myarr as $key=>$val) {
//exec sql
}