前言:
在MYSQL資料庫的使用中,業務資料的增删改查離不開資料治理,當然,這就會涉及到資料庫系統内置的一些文本處理函數的使用,來實作資料的規範處理,達到業務應用的目的,涉及到的方法可能包含以下内容:
1、替換:replace(需替換的字段,被替換的字元,替換的内容)
2、截取:substr(需處理的數字和字元串,從1開始的下标序号,截取字元的長度)
3、分割:substring_index(字段,分割符号,M) M指第幾個分割符,有正負之分
4、拼接:concat(字段1,字段2,字段3,......)
5、字串檢索:locate(待檢索的字串,字段,檢索起始位置[數字,預設1])
6、小寫轉換:lower(待轉換的字串)
7、大寫轉換:upper(待轉換的字串)
8、長度傳回:length(待計算長度的字串)
9、左截取:left(待提取的字元串,指定将從左邊傳回的字元數)
10、右截取:right(待提取的字元串,指定将從右邊傳回的字元數)
11、删除指定字串:trim(both| leading | trailing 子串 from 原始字段)
12、清除左空格:ltrim(需要删除左側空格的字元串)
13、清除右空格:rtrim(需要删除右側空格的字元串)
14、傳回字元串的位置:position(在字元串中搜尋的子串 in 要搜尋的原始字元串)
模拟資料:
圖1-總模拟資料
應用1、替換:replace(需替換的字段,被替換的字元,替換的内容)
select id,other_name,replace(other_name,'_','替換内容') from class_score where id = 2
查詢結果:
圖2-replace
應用2、截取:substr(需處理的數字和字元串,從1開始的下标序号,截取字元的長度)
select id,bobby,substr(bobby,1,4) from class_score where id = 2
查詢結果:
圖3-substr
應用3、分割:substring_index(字段,分割符号,M) M指第幾個分割符,有正負之分
select id,bobby,substring_index(bobby,',',1) from class_score where id = 2 //若M數字為正,從左往右,查詢的是第M分隔符左邊所有的内容
查詢結果:
圖4-substring_index
select id,bobby,substring_index(bobby,',',-1) from class_score where id = 2 ////若M數字為負,從右往左,查詢的是第|M|分隔符右邊所有的内容
查詢結果:
圖5-substring_index
應用4、拼接:concat(字段1,字段2,字段3,......)
select id,name,six,subject,concat(name,'-',six,'-',subject) as desc_ from class_score
查詢結果:
圖6-concat
應用5、字串檢索:locate(待檢索的字串,字段,檢索起始位置[數字,預設1])
select id,name,other_name,locate('a',other_name,2) as desction from class_score where id = 12
從other_name查找a第一次出現的位置。如果a不在other_name中,則傳回值為0。
查詢結果:
圖7-locate
應用6、小寫轉換:lower(待轉換的字串)
select id,name,other_name,lower(other_name) from class_score where id = 2
查詢結果:
圖8-lower
應用7、大寫轉換:upper(待轉換的字串)
select id,name,other_name,upper(other_name) from class_score where id = 1
查詢結果:
圖9-upper
應用8、長度傳回:length(待計算長度的字串)
select id,name,other_name,length(other_name) from class_score where id = 2
查詢結果:
圖10-length
應用9、左截取:left(待提取的字元串,指定将從左邊傳回的字元數)
select id,name,other_name,left(other_name,2) from class_score where id = 12
查詢結果:
圖11-left
應用10、右截取:right(待提取的字元串,指定将從右邊傳回的字元數)
select id,name,other_name,right(other_name,3) from class_score where id = 12
查詢結果:
圖12-right
應用11、删除指定字串:trim(both| leading | trailing 子串 from 原始字段)
SELECT
trim( ' xhx ' ) AS '删除指定字元串中的空格',
trim( LEADING 'x' FROM 'xxhhxx' ) AS '删除指定的首字元',
trim( BOTH 'x' FROM 'xxxhhhxxxhhhxxx' ) AS '删除指定的首尾字元',
trim( TRAILING 'x' FROM 'xxxhhhxxxhhhxxx' ) AS '删除指定的尾字元'
查詢結果:
圖13-trim
應用12、清除右空格:rtrim(需要删除右側空格的字元串)
SELECT rtrim( ' xhx ' ) AS '清除右邊空格',REPLACE ( rtrim( ' xhx ' ), ' ', '-' ) AS '驗證結果'
查詢結果:
圖14-rtrim
應用13、清除左側空格:ltrim(需要删除左側空格的字元串)
SELECT ltrim( ' xhx ' ) AS '清除左側空格',REPLACE ( ltrim( ' xhx ' ), ' ', '-' ) AS '驗證結果'
查詢結果:
圖15-ltrim
應用14、傳回字元串的位置:position(在字元串中搜尋的子串 in 要搜尋的原始字元串)
SELECT POSITION('a' in 'saggxx') as '字元a出現的位置' //若字元串沒有所查詢的字元則傳回0
查詢結果:
圖16-position