Home > Database > Mysql Tutorial > How to use the SUBSTRING() function in MySQL

How to use the SUBSTRING() function in MySQL

WBOY
Release: 2023-06-02 23:32:27
forward
3740 people have browsed it

SUBSTRING()

SUBSTRING(str,pos)SUBSTRING(str FROM pos)SUBSTRING(str,pos,len) and SUBSTRING(str FROM pos FOR len) functions can be used to return the substring starting from the specified position pos, len means the length of the returned substring; pos is 0 means returning an empty string. For example:

SELECT SUBSTRING('MySQL字符串函数', -2) AS str1,
       SUBSTRING('MySQL字符串函数', -5, 3) AS str2;
str1  |str2  |
------+------+
函数  |字符串 |
Copy after login

The positional parameter pos can be a negative number, in which case the returned substring starts from the pos character on the right side of the string. For example:

SELECT LEFT('MySQL字符串函数',5) AS str1,
       RIGHT('MySQL字符串函数',5) AS str2;
str1 |str2     |
-----+---------+
MySQL|字符串函数|
Copy after login
Copy after login

In addition, the SUBSTR() and MID() functions are synonyms of the SUBSTRING() function and also support the above 4 forms.

LEFT(str,len)The function returns the len characters on the left side of the string str, RIGHT(str,len)The function returns the len characters on the right side of the string str len characters. For example:

SELECT LEFT('MySQL字符串函数',5) AS str1,
       RIGHT('MySQL字符串函数',5) AS str2;
str1 |str2     |
-----+---------+
MySQL|字符串函数|
Copy after login
Copy after login

SUBSTRING_INDEX(str,delim,count)The function returns the substring before the count delimiter delim. If count is positive, count from the left and return all characters on the left; if count is negative, count from the right and return all characters on the right. For example:

SELECT SUBSTRING_INDEX('张三;李四;王五', ';', 2) AS str1,
       SUBSTRING_INDEX('张三;李四;王五', ';', -2) AS str2;
str1    |str2    |
--------+--------+
张三;李四|李四;王五|
Copy after login

The above is the detailed content of How to use the SUBSTRING() function in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template