[MySQL] 字串取代與連接 (REPLACE、CONCAT)

取代字串:REPLACE(`欄位名稱`, '欲取代的字串', '取代後的字串')

1
2
3
4
5
6
# 將efg開頭的字串取代
UPDATE table SET column = REPLACE(column, 'efg', 'zzz') WHERE column LIKE 'efg%';
將efg結尾的字串取代
UPDATE table SET column = REPLACE(column, 'efg', 'zzz') WHERE column LIKE '%efg';
將欄位column_2含有efg字串取代成zzz,不過將取代後的結果覆寫於column_1,不更動column_2原有的內容
UPDATE table SET column_1 = REPLACE(column_2, 'efg', 'zzz') WHERE column_2 LIKE '%efg%';

連接字串:CONCAT('字串1', '字串2', ... '字串n')

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 於column值為456的資料行首插入字串123
UPDATE table SET column = CONCAT('123', column) WHERE column='456';
(Result: 123456)
# 於column值為456的資料行尾插入字串123
UPDATE table SET column = CONCAT(column, '123') WHERE column='456';
(Result: 456123)
# 於column值為456的資料行首插入字串123,行尾插入789
UPDATE table SET column = CONCAT('123', column, '789') WHERE column='456';
(Result: 123456789)
於column值為456的資料行首行尾各插入原值,使其值為重覆三次的字串
UPDATE table SET column = CONCAT(column, column, column) WHERE column='456';
(Result: 456456456)
Licensed under CC BY-NC-SA 3.0 TW
最後更新 2023-02-21
comments powered by Disqus