通常我使用手动查找替换文本在MySQL数据库使用phpMyAdmin。我现在厌倦了,我怎么能运行一个查询,在phpMyAdmin的整个表中找到和替换一个新的文本?

例如:查找关键字domain。例如,替换为www.domain.example。


当前回答

我发现的最简单的方法是将数据库转储到一个文本文件中,运行sed命令进行替换,然后将数据库重新加载回MySQL。

下面所有命令都是Linux下的bash命令。

转储数据库到文本文件

mysqldump -u user -p databasename > ./db.sql

执行sed命令查找/替换目标字符串

sed -i 's/oldString/newString/g' ./db.sql

重新加载数据库到MySQL

mysql -u user -p databasename < ./db.sql

容易peasy。

其他回答

对于单个表更新

 UPDATE `table_name`
 SET `field_name` = replace(same_field_name, 'unwanted_text', 'wanted_text')

从多个表-

如果您希望从所有表中进行编辑,最好的方法是获取转储,然后查找/替换并上传回来。

UPDATE  `MySQL_Table` 
SET  `MySQL_Table_Column` = REPLACE(`MySQL_Table_Column`, 'oldString', 'newString')
WHERE  `MySQL_Table_Column` LIKE 'oldString%';

在phpMyAdmin中运行SQL查询来查找和替换所有WordPress博客文章中的文本,例如查找mysite。Example /wordpress,然后用mysite。Example /news替换 本例中的表为tj_posts

UPDATE `tj_posts`
SET `post_content` = replace(post_content, 'mysite.example/wordpress', 'mysite.example/news')

在有大小写字母的句子中, 我们可以使用二进制REPACE

UPDATE `table_1`  SET  `field_1` =  BINARY REPLACE(`field_1`, 'find_string', 'replace_string')

把它放到一个php文件中,然后运行它,它应该做你想做的事情。

// Connect to your MySQL database.
$hostname = "localhost";
$username = "db_username";
$password = "db_password";
$database = "db_name";

mysql_connect($hostname, $username, $password);

// The find and replace strings.
$find = "find_this_text";
$replace = "replace_with_this_text";

$loop = mysql_query("
    SELECT
        concat('UPDATE ',table_schema,'.',table_name, ' SET ',column_name, '=replace(',column_name,', ''{$find}'', ''{$replace}'');') AS s
    FROM
        information_schema.columns
    WHERE
        table_schema = '{$database}'")
or die ('Cant loop through dbfields: ' . mysql_error());

while ($query = mysql_fetch_assoc($loop))
{
        mysql_query($query['s']);
}