Usage of substring truncation functions in MySql

Source: Internet
Author: User

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'

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.