Home  >  Article  >  Database  >  Detailed explanation of the usage of MySQL MID() function (code example)

Detailed explanation of the usage of MySQL MID() function (code example)

藏色散人
藏色散人Original
2019-03-28 10:00:346932browse

In MySQL, the MID() function returns the substring starting from the specified position.

MID() and SUBSTR() are both synonyms of SUBSTRING().

The basic syntax is this:

MID(str,pos,len)

Here, str is a string, pos is the position of the starting substring, and len is an optional parameter that determines the return from the starting position number of characters.

There are several different ways to use this function, so the complete syntax looks like this:

MID(str,pos)
MID(str FROM pos)
MID(str,pos,len)
MID(str FROM pos FOR len)

Example 1 - Basic Usage

Here is an example of MID(str,pos) syntax:

SELECT MID('I drink coffee', 3) Result;

Result:

+--------------+
| Result       |
+--------------+
| drink coffee |
+--------------+

In this example, I take a substring from the string, from the position 3 starts.

Example 2 - Using FROM clause

This time the MID(str FROM pos) syntax is used:

SELECT MID('I drink coffee' FROM 3) Result;

Result:

+--------------+
| Result       |
+--------------+
| drink coffee |
+--------------+

The result is the same.

In this example, FROM is standard SQL. Note that this syntax does not use commas.

Example 3 - Specify length

In this example, I used the MID(str,pos,len) syntax:

SELECT MID('I drink coffee', 3, 5) Result;

Result:

+--------+
| Result |
+--------+
| drink  |
+--------+

Here I specify that the length of the returned substring is 5 characters.

Example 4 - Specifying length (using FOR clause)

In this example, I used the MID(str FROM pos FOR len) syntax:

SELECT MID('I drink coffee' FROM 3 FOR 5) Result;

Result:

+--------+
| Result |
+--------+
| drink  |
+--------+

So, this time we use standard SQL to achieve the same result.

Related recommendations: "MySQL Tutorial"

This article is a detailed explanation of the usage of the MySQL MID() function. It is simple and easy to understand. I hope it will be helpful to friends who need it. help!

The above is the detailed content of Detailed explanation of the usage of MySQL MID() function (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn