UPDATE table_name SET column_name = REPLACE(column_name, 'old_substring', 'new_substring') WHERE column_name LIKE '%old_substring%'; -- 建議加 WHERE 減少無意義更新
采集數據標題含垃圾片段:<img src="images/awwor.gif">,導致前端顯示異常。需批量清除。
UPDATE `article` SET `title` = REPLACE(`title`, '<img src="images/awwor.gif">', '') WHERE `title` LIKE '%<img src="images/awwor.gif">%';
-- 1. 預覽影響範圍
SELECT COUNT(*) FROM `article` WHERE `title` LIKE '%<img src="images/awwor.gif">%';
-- 2. 預覽替換後樣本
SELECT `title` AS old_title,
REPLACE(`title`, '<img src="images/awwor.gif">', '') AS new_title
FROM `article`
WHERE `title` LIKE '%<img src="images/awwor.gif">%' LIMIT 10;
-- 3. 事務包裹執行 (生產環境)
START TRANSACTION;
UPDATE `article` SET `title` = REPLACE(`title`, '<img src="images/awwor.gif">', '') WHERE `title` LIKE '%...%';
-- 檢查 ROW_COUNT() 是否符合預期
COMMIT; -- 或 ROLLBACK;
UPDATE `content` SET `body` = REPLACE(REPLACE(REPLACE(`body`, '<script>', ''), '</script>', ''), '<iframe>', '') WHERE `body` LIKE '%<script>%' OR `body` LIKE '%<iframe>%';
-- 僅替換完整標籤,避免誤傷相似文本 UPDATE `article` SET `title` = REGEXP_REPLACE(`title`, '<img\s+src=["\']images/awwor\.gif["\']\s*/?>', '') WHERE `title` REGEXP '<img\s+src=["\']images/awwor\.gif["\']\s*/?>';
UPDATE `article`
SET `title` = REPLACE(`title`, 'old', 'new'),
`title_search_vector` = REPLACE(`title_search_vector`, 'old', 'new'), -- 若有全文搜索向量列
`updated_at` = NOW()
WHERE `title` LIKE '%old%';
| 問題 | 原因 | 解決 |
|---|---|---|
| 全表掃描慢 | 無 WHERE 或 LIKE '%...%' 不走索引 | 加 WHERE 過濾;全文索引 MATCH...AGAINST;分批次更新 (LIMIT 1000 循環) |
| 誤替換 (如替換 'a' 導致 'abc' 變 'bc') | REPLACE 是**全局子串替換**,無單詞邊界概念 | 盡量精確匹配長子串;8.0 用 REGEXP_REPLACE 加邊界 \b |
| 觸發器/外鍵級聯放大影響 | 更新觸發關聯表操作 | 評估影響範圍;必要時暫停觸發器 SET FOREIGN_KEY_CHECKS=0 (極慎重) |
| 主從延遲 | 大量更新產生巨大 Binlog | 分批次、低峰期執行;SET sql_log_bin=0 (僅當前會話不記 Binlog,極慎重) |
REPLACE(str, from, to) 是 MySQL 最高效的**全量子串替換**工具。REGEXP_REPLACE。