在mysql字符替換我們常用用update更新語(yǔ)句與replace替換函數(shù)進(jìn)行操作,我們可以利用where來(lái)限制是替換指定內(nèi)容還是替換所有內(nèi)容,下面一起來(lái)看看相關(guān)教程.
replace替換:mysql中replace函數(shù)直接替換mysql數(shù)據(jù)庫(kù)中某字段中的特定字符串,不再需要自己寫函數(shù)去替換,用起來(lái)非常的方便,mysql 替換函數(shù)replace().
replace:replace(str1, str2, str3),例子代碼如下:
UPDATE `table_name` SET `field_name` = replace (`field_name`,'from_str','to_str') WHERE `field_name` LIKE '%from_str%'
說(shuō)明:
table_name —— 表的名字
field_name —— 字段名
from_str —— 需要替換的字符串
to_str —— 替換成的字符串
例如,mysql替換表的字段里面內(nèi)容,代碼如下:
- mysql> select id,type from items limit 10;
- +--------+--------+
- | id | type |
- +--------+--------+
- | 0001 | 780000 |
- | 0002 | 780000 |
- | 0003 | 780000 |
- | 0004 | 780000 |
- | 0005 | 780000 |
- | 150419 | 780000 |
- | 150420 | 780000 |
- | 150421 | 780000 |
- | 150422 | 780000 |
- | 150423 | 780000 |
- +--------+--------+
把type字段中的“78”改成“79” 用replace函數(shù),sql如下:
- mysql> update items set type=replace(type,'79','78');
- Query OK, 17536 rows affected (0.72 sec)
- Rows matched: 17536 Changed: 17536 Warnings: 0
再查詢,代碼如下:
- mysql> select id,type from items limit 10;
- +--------+--------+
- | id | type | m.survivalescaperooms.com
- +--------+--------+
- | 0001 | 790000 |
- | 0002 | 790000 |
- | 0003 | 790000 |
- | 0004 | 790000 |
- | 0005 | 790000 |
- | 150419 | 790000 |
- | 150420 | 790000 |
- | 150421 | 790000 |
- | 150422 | 790000 |
- | 150423 | 790000 |
- +--------+--------+
- 10 rows in set (0.00 sec)
由查詢結(jié)果到,數(shù)據(jù)已經(jīng)更新成功.
正則替換 locate:
LOCATE(substr,str)
POSITION(substr IN str)
返回子串 substr 在字符串 str 中第一次出現(xiàn)的位置,如果子串 substr 在 str 中不存在,返回值為 0:
substring
SUBSTR(str,pos,len): 由<str>中的第<pos>位置開始,選出接下去的<len>個(gè)字元.
首先描述一下,我遇到的問(wèn)題,以下是數(shù)據(jù)庫(kù)中的一個(gè)表mt2:
- +----+------------------------------------------+
- | id | name |
- +----+------------------------------------------+
- | 1 | sdfsf<contact>beijing</contact>sldjfsld |
- | 2 | sdfsf<contact>shanghai</contact>sldjfsld |
- | 3 | sdfsf<contact>jn</contact>sldjfsld |
- | 4 | sdfsf<contact>qd</contact>sldjfsld |
- +----+------------------------------------------+
遇到的要求是:將該表中<contact>到</contact>的內(nèi)容刪除,眾所周知,replace函數(shù)是不支持正則表達(dá)式的,所以只能采用其他的方法處理.
于是,我是使用了下面的sql語(yǔ)句:
update mt2 set name = replace(name, substring(name, locate('<contact>', name),locate('</contact>', name)-locate('<contact>'+10, name)),'');
問(wèn)題解決了,結(jié)果如下:
- +----+-------------------+
- | id | name |
- +----+-------------------+
- | 1 | sdfsfactsldjfsld |
- | 2 | sdfsfactsldjfsld |
- | 3 | sdfsfactsldjfsld |
- | 4 | sdfsfactsldjfsld |
- +----+-------------------+
新聞熱點(diǎn)
疑難解答
圖片精選