The commonly used string truncation functions in mysql include substring and SUBSTRING_INDEX. substring is the string whose pos starts to be len. This is a bit like the php string truncation function, let's take a look.
Usage:
SUBSTRING (str, pos, len)
SUBSTRING (str FROM pos FOR len)
SUBSTRING (str, pos)
SUBSTRING (str FROM pos)
Alias SUBSTR
Truncates a string whose str starts from the pos and is len. If the len parameter is not set, all content after the pos is obtained by default.
Note that the index of the string starts from 1.
If pos is a negative number, it is truncated from the end of the string.
1. truncate all pos data
The Code is as follows: |
Copy code |
Mysql> select substring ('mysql database', 2 ); + ----------- + | Substring ('mysql database', 2) | + ----------- + | Ysql database | + ----------- + 1 row in set |
2. truncate the last three characters of the pos
The Code is as follows: |
Copy code |
Mysql> select substring ('mysql database', 2, 3 ); + ----------- + | Substring ('mysql database', 2, 3) | + ----------- + | Ysq | + ----------- + 1 row in set |
3. view some other instances
The Code is as follows: |
Copy code |
Mysql> select substring ('quadratically ', 5 ); -> 'Ratically' Mysql> select substring ('foobarbar' FROM 4 ); -> 'Barbar' Mysql> select substring ('quadratically ', 5, 6 ); -> 'Ratica' Mysql> select substring ('sakila',-3 ); -> 'Ila' Mysql> select substring ('sakila',-5, 3 ); -> 'Aki' Mysql> select substring ('sakila' FROM-4 FOR 2 ); -> 'Ki' |
Now, let's take a look.
Substring_index
Substring_index (str, delim, count)
The Code is as follows: |
Copy code |
Mysql> SELECT SUBSTRING_INDEX ('www. bKjia. c0m', '.', 2 ); -> 'Www. 111cn' Mysql> SELECT SUBSTRING_INDEX ('www. bKjia. c0m', '.',-2 ); -> 'Bkjia. c0m' |