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 | ------+------+ 函数 |字符串 |
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|字符串函数|
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|字符串函数|
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 | --------+--------+ 张三;李四|李四;王五|
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!