基本語法
UPDATE `table_name`
SET `field_name` = REPLACE(`field_name`, 'from_str', 'to_str')
WHERE `field_name` LIKE '%from_str%';
table_name:目標表名
field_name:目標欄位
from_str:被替換子字串 (支援任意字元,非正則)
to_str:替換後字串
實戰範例
範例 1:副檔名批量修正
UPDATE `attachments`
SET `filename` = REPLACE(`filename`, '.rar', '.7z')
WHERE `filename` LIKE '%.rar';
範例 2:BBCode 標籤統一
UPDATE `boblog_blogs`
SET `content` = REPLACE(`content`, '[mycode=xml]', '[mycode=html]');
UPDATE `boblog_blogs`
SET `content` = REPLACE(`content`, '[//mycode]', '[/mycode]');
範例 3:狀態值翻轉
UPDATE `boblog_blogs`
SET `htmlstat` = 0
WHERE `htmlstat` = 1;
效能提示
REPLACE 為**全字串掃描替換**,非正則,速度極快。
- 大表操作建議:
WHERE`field_name` LIKE '%from_str%' 先過濾,避免全表掃描。
- 若需正則替換,MySQL 8.0+ 可用
REGEXP_REPLACE,但效能遠低於 REPLACE,非必要勿用。
進階:多欄位同時替換
UPDATE `products`
SET
`title` = REPLACE(`title`, '舊品牌', '新品牌'),
`description` = REPLACE(`description`, '舊品牌', '新品牌')
WHERE `title` LIKE '%舊品牌%' OR `description` LIKE '%舊品牌%';