我們知道在MySQL字符串截取函數有:left(),right(),substring(),substring_index(),還有mid(),substr().其中,mid這些,下面我來給大家說明這些字符截函數的用法.
substr() 等價于substring() 函數,substring()的功能非常強大和靈活.
1、從左開始截取字符串
left(str, length)
說明:left(被截取字段,截取長度)
left(str,length); select left ('hxsdit.com',3);結果是hxs
2、right(str,length);
從右開始截取字符串:right(str, length)
說明:right(被截取字段,截取長度)
select right('hxsdit.com,3 ); 結果是com.
3、substring(str,pos,length)
截取字符串:
- substring(str, pos)
- substring(str, pos, length)
說明:substring(被截取字段,從第幾位開始截取)
substring(被截取字段,從第幾位開始截取,截取長度)
select substring('Vevb.com',4)從字符串str第四個字符位置開始截取,直到結束,結果為fensi.com
select substring('Vevb.com',4,2) 從字符串str第四個字符位置開始截取,截取2個.結果為fe
select substring('hxsdit.com'-4)從字符串str倒數第四個開始截取,直到結束。 結果為.com
select substring('hxsdit.com'-4,2)從字符串str倒數第四個開始截取,截取2個 結果為.c,使用這個函數時候請注意,變量pos可以為負值,但是length不可以為負值.
4、substring_index(str,delim,count);
按關鍵字截取字符串:substring_index(str,delim,count)
說明:substring_index(被截取字段,關鍵字,關鍵字出現的次數),代碼如下:
select substring_index('www.baidu.com','.',2); 截取第二個'.'之前的所有字符 結果為 www.baidu
select substring_index('www.baidu.com','.',-2); 截取倒數第二個'.'之后的所有字符 結果為 com
select substring_index('www.baidu.com','234',1); 如果在字符串中找不到delim參數指定的值,就返回整個字符串
截取第二個 '.' 之前的所有字符,代碼如下:
- mysql> select substring_index('www.sqlstudy.com.cn', '.', 2);
- +------------------------------------------------+
- | substring_index('www.sqlstudy.com.cn', '.', 2) |
- +------------------------------------------------+
- | www.sqlstudy |
- +------------------------------------------------+
4.2 截取第二個 '.' (倒數)之后的所有字符,代碼如下:
- mysql> select substring_index('www.sqlstudy.com.cn', '.', -2);
- +-------------------------------------------------+
- | substring_index('www.sqlstudy.com.cn', '.', -2) |
- +-------------------------------------------------+
- | com.cn |
- +-------------------------------------------------+
5、如果在字符串中找不到 delim 參數指定的值,就返回整個字符串,代碼如下:
- mysql> select substring_index('www.sqlstudy.com.cn', '.coc', 1);
- +---------------------------------------------------+
- | substring_index('www.sqlstudy.com.cn', '.coc', 1) |
- +---------------------------------------------------+
- | www.sqlstudy.com.cn |
- +---------------------------------------------------+
新聞熱點
疑難解答