mysql中的字符串截取和替換


-- 替換 replace(字段名,"需要替換的字符","替換的字符") mysql里replace不支持正則匹配
mysql> set @needReplaceStr = 'hello world!';
Query OK, 0 rows affected (0.00 sec)

mysql> select replace(@needReplaceStr, 'world', 'leyi');
+-------------------------------------------+
| replace(@needReplaceStr, 'world', 'leyi') |
+-------------------------------------------+
| hello leyi!                               |
+-------------------------------------------+
1 row in set (0.00 sec)


— 字符串截取的方式替換 SUBSTRING instr或locate
mysql> set @needReplaceStr = 'hello world!';
Query OK, 0 rows affected (0.00 sec)

— 等同於 
select concat(SUBSTRING(@needReplaceStr,1, locate(' ',@needReplaceStr)), 'leyi!');

mysql> select concat(SUBSTRING(@needReplaceStr,1, instr(@needReplaceStr,' ')), 'leyi!');
+---------------------------------------------------------------------------+
| concat(SUBSTRING(@needReplaceStr,1, instr(@needReplaceStr,' ')), 'leyi!') |
+---------------------------------------------------------------------------+
| hello leyi!                                                               |
+---------------------------------------------------------------------------+
1 row in set (0.00 sec)


— left right 截取前幾位和后幾位字符

mysql> set @needReplaceStr = 'hello world!';
Query OK, 0 rows affected (0.00 sec)

mysql> select concat(left(@needReplaceStr, 5), ' leyi!');
+--------------------------------------------+
| concat(left(@needReplaceStr, 5), ' leyi!') |
+--------------------------------------------+
| hello leyi!                                |
+--------------------------------------------+
1 row in set (0.00 sec)

— SUBSTRING_INDEX(str,delim,count)  
— 如果count是正數,那么就是從左往右數,第N個分隔符的左邊的全部內容
— 如果是負數,那么就是從右邊開始數,第N個分隔符右邊的所有內容
e.g 截取最后一個逗號之后的內容
select reverse(SUBSTRING_INDEX(reverse('abc,bde,cfg,dfh,ebv'),',',1))
select SUBSTRING_INDEX('abc,bde,cfg,dfh,ebv',',',-1)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM