資料遷移或系統整合時,常遇到欄位內夾雜不規則路徑,需批量替換為統一格式。MySQL 內建 LOCATE() 定位子串位置、REPLACE() 全量替換,配合 SUBSTRING() 即可靈活處理「前綴固定、中間 ID 變動、後綴固定」的模式化字串。本文以實戰案例示範 4000 條記錄的路徑重寫。
表 field_data_body,欄位 body_value 存放富文本內容,夾雜兩類歷史路徑:
/eapdomain/UserFiles/1073/Image/... (1073 為用戶 ID,動態變化)/eapdomain/UserFiles/1073/File/...目標:統一替換為 /sites/default/files/old/image/ 與 /sites/default/files/old/file/。
| 函數 | 語法 | 說明 |
|---|---|---|
| LOCATE | LOCATE(substr, str, [pos]) | 返回 substr 在 str 中首次出現位置(1-based),找不到返回 0 |
| SUBSTRING | SUBSTRING(str, pos, len) | 從 pos 截取長度 len 的子串 |
| REPLACE | REPLACE(str, from_str, to_str) | 將 str 中所有 from_str 替換為 to_str |
利用 LOCATE 定位固定前綴 /eapdomain/UserFiles/ 與固定後綴 /Image/(或 /File/),計算中間動態段長度,提取完整舊路徑並整體替換:
-- 替換 Image 路徑
UPDATE field_data_body
SET body_value = REPLACE(
body_value,
SUBSTRING(
body_value,
LOCATE('/eapdomain/UserFiles/', body_value),
LOCATE('/Image/', body_value) + 7 - LOCATE('/eapdomain/UserFiles/', body_value)
),
'/sites/default/files/old/image/'
)
WHERE body_value LIKE '%/eapdomain/UserFiles/%/Image/%';
-- 替換 File 路徑
UPDATE field_data_body
SET body_value = REPLACE(
body_value,
SUBSTRING(
body_value,
LOCATE('/eapdomain/UserFiles/', body_value),
LOCATE('/File/', body_value) + 6 - LOCATE('/eapdomain/UserFiles/', body_value)
),
'/sites/default/files/old/file/'
)
WHERE body_value LIKE '%/eapdomain/UserFiles/%/File/%';
LOCATE('/eapdomain/UserFiles/', body_value) → 起始位置LOCATE('/Image/', body_value) + 7 → 結束位置(含 /Image/ 7 字元)SUBSTRING 精準切出完整舊路徑REPLACE 全文替換該路徑為新前綴WHERE 子句先過濾,避免全表掃描與無意義更新REPLACE 預設替換所有匹配,單條 SQL 即可覆蓋同一欄位多個舊路徑。COLLATE utf8mb4_bin。WHERE id BETWEEN ... AND ... 並加上 LIMIT,避免長鎖表。mysqldump 或建立臨時表驗證。UPDATE target_table
SET target_col = REPLACE(
target_col,
SUBSTRING(
target_col,
LOCATE('fixed_prefix', target_col),
LOCATE('fixed_suffix', target_col) + CHAR_LENGTH('fixed_suffix') - LOCATE('fixed_prefix', target_col)
),
'new_unified_prefix'
)
WHERE target_col LIKE '%fixed_prefix%fixed_suffix%';
掌握 LOCATE + SUBSTRING + REPLACE 組合拳,即可在 SQL 層面完成 90% 的非結構化字串清洗工作,無需導出到應用層處理,大幅提升資料治理效率。