Categories
學習筆記

MySQL的replace指令 搜索並替換子字串

想法如下,我們要做的是update某張table,爲指定attribute設定新的值。 而該新的值是利用replace function處理過的。 先簡單介紹一下replace的使用方法。 replace('所要搜索的字串','想替換的子字串','替換後的子字串'); 比如我有一個字串是abc,我想把a替換成d,則可如下使用: replace('abc','a','d'); 另外update某表的中指定attribute的方法如下,下面的例子是將table中from的值是b的update爲a: update `table` set `from`='a' where `from`='b'; 現在進入正題: 下面的例子是某程序email template的情況,其table如下圖所示,from的值都是[email protected],我想把from的值改爲[email protected]。 首先我們可以先單純測試一下replace function確定我們的replace是否如我們預期能夠正確替換。 select replace('[email protected]','www.',''); 結果如上圖所示,正確替換了,現在我們來做替換整張table中from這個attribute的動作 update `emails` set `from`=replace(`from`,'www.',''); 結果就變成這樣了,如預期的一樣。