REPLACE(str, from_str, to_str)
-- 返回将 str 中所有 from_str 替换为 to_str 后的字符串
UPDATE b_blog
SET content = REPLACE(content, 'www.111cn.net', 'm.111cn.net')
WHERE id = 9;
需求:清理 message 字段中从 [b][url] [img] 到 [/url][/b] 的整段内容。
UPDATE b_blog
SET message = REPLACE(
message,
SUBSTRING(
message,
LOCATE('[b][url] [img]', message),
LOCATE('[/url][/b]', message) + 10 - LOCATE('[b][url] [img]', message)
),
''
)
WHERE id >= 10000;
pos:起始位置(1-based),负数表示从末尾倒数。len:长度,可选,省略则截至末尾。SUBSTRING('blog.fity.cn', 6, 4) → 'fity'substr 在 str 中首次出现的位置(1-based),不存在返回 0。pos 指定搜索起始位置。LOCATE('fity', 'blog.fity.cn') → 6UPDATE articles
SET content = REPLACE(
REPLACE(
REPLACE(content, 'old1', 'new1'),
'old2', 'new2'),
'old3', 'new3');
UPDATE posts
SET content = TRIM(REPLACE(content, ' ', ' '))
WHERE content LIKE '% %';
UPDATE logs
SET message = REPLACE(message, SUBSTRING(message, LOCATE('[ERROR]', message), 50), '[REDACTED]')
WHERE message REGEXP '\\[ERROR\\]';
REPLACE 会全表扫描,大表建议分批次(LIMIT + WHERE id > last_id)执行。SELECT 预览受影响行,确认无误再 UPDATE。START TRANSACTION; ... COMMIT/ROLLBACK; 保证原子性。