替换所有表上的值

时间:2016-02-10 10:53:25

标签: mysql sql

我想在MySQL数据库的所有表中用another_email@example.com替换电子邮件地址email@example.com。我怎么能这样做?

4 个答案:

答案 0 :(得分:0)

使用MySQL Workbench,您可以搜索"Database" -> "Search Table Data" menu option.

中的字符串

指定LIKE %URL_TO_SEARCH%,在左侧选择要搜索的所有表格。您可以使用"Cntrl + A"选择左侧的整个树,然后取消选择您不关心的对象。 enter image description here

答案 1 :(得分:0)

您可以使用以下存储过程 -

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_email_update`()
BEGIN
DECLARE done INT(1) DEFAULT 0;
DECLARE _table_name VARCHAR(100) DEFAULT '';
DECLARE cur1 CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema='test' AND table_type='base table';
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;
OPEN cur1;

REPEAT
FETCH cur1 INTO _table_name;
IF _table_name = '' THEN
    SET done = 1;
END IF;
             IF (done<>1) THEN
                             SET @str1=CONCAT("UPDATE ",_table_name," SET column1='another_email@example.com' WHERE column1='email@example.com'");
                 PREPARE stmt1 FROM @str1;
                 EXECUTE stmt1;
                 DEALLOCATE PREPARE stmt1;

            END IF;
UNTIL done=1
END REPEAT;
     CLOSE cur1;
     SELECT 'done';
END$$

DELIMITER ;

在db中创建上述过程,您要在其中更改所有表的此电子邮件值。

并使用以下语句更改值 -

call sp_email_update();

注意:根据您的要求更改更新查询。如果想要所有电子邮件,请删除条件。

答案 2 :(得分:0)

你可以使用这个:

<?php

/**
 * do find & replace for a specific value of field in all the databse tables dynamicly.
 * @author Masoud
 * @link  https://github.com/massooti/db_find_replace.git
 */

$pdo = new PDO('mysql:host=db_host;dbname=db_name', 'db_user', 'db_password');

//Our SQL statement, which will select a list of tables from the current MySQL database.
$sql = "SHOW TABLES";

//////Prepare our SQL statement,
$t_statement = $pdo->prepare($sql);

////Execute the statement.
$t_statement->execute();

////Fetch the tables from our statement.
$tables = $t_statement->fetchAll(PDO::FETCH_NUM);

foreach ($tables as $table) {

    $sql = "SHOW COLUMNS FROM $table[0]";

    $c_statement = $pdo->prepare($sql);
    $c_statement->execute();

    $raw_column_data = $c_statement->fetchAll(PDO::FETCH_ASSOC);

    foreach ($raw_column_data as $key => $column) {
        $field = $column['Field'];
        $command = "UPDATE  `$table[0]` SET  `$field` =
                REPLACE($field, 'old_strings', 'new_strings')
                WHERE  $field LIKE 'old_strings%';";
        $f_statement = $pdo->prepare($command);
        $f_statement->execute();
    }
}
?>

答案 3 :(得分:-1)

为所有可以使用电子邮件ID列的表编写此查询。

UPDATE table_name
SET column1='another_email@example.com'
WHERE column1='email@example.com'