substring_index与 replace的使用
主要用来对数据库的已有信息进行字符串截取与替换
使用情景:
现在有需求需要分别拿到省市区信息,而不是一个字符串,这时候思路一就是先select出来,在后台通过split(",")拆分为String数组,然后通过下标一一获取省市区的信息,OK没问题。但是当数据量成千上万的时候,我需要先获取再分割再赋值,会严重影响效率。这时候通过MySQL的substring_index在获取的时候就进行分割要快的多。同样也适用于字符串的替换,比如说将分隔符‘,’改为‘-’,使用replace也可以避免后台的二次处理。
substring_index(str,delim,count)
说明:substring_index(被截取字段,关键字,关键字出现的次数)
(注:如果关键字出现的次数是负数 如-2 则是从后倒数,到字符串结束)
实例代码:
SELECT
substring_index(merge_name,',', 1) as provinceName,
substring_index(substring_index(merge_name,',', -2), ',', 1) as cityName,
substring_index(merge_name,',', -1) as countryName
from t_r_area where uuid='150304'
运行结果:
replace(str, ‘original’,‘replace’)
说明:str要替换的字符串,original被替换的字符,replace新的字符
示例代码:
SELECT REPLACE(merge_name,',','-') as mergeName
from t_r_area where uuid='150304'
运行结果:
除了这两个字符串操作函数之外还有别的字符串切割的方法,这是两个较为常用的,更多方法见博客MySQL字符串截取