3 extraction methods: 1. Use the SUBSTRING() function to intercept a substring of a specified length from the head of the string. The syntax is "UBSTRING(string, 1, substring length)". 2. Use the left() function to intercept a substring of a specified length from the beginning of the string and return it. The syntax is "LEFT (string, substring length)". 3. Use the substr() function to intercept a substring of specified length from the beginning of the string and return it. The syntax is "SUBSTR(string, 1, substring length)".
The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.
Mysql 3 ways to get the first digits of a string:
Method 1: Use the SUBSTRING() function
SUBSTRING() function can intercept a string and return a substring of specified length starting from the specified position
SUBSTRING(string, start, length)
Parameters | Description |
---|---|
string | Required. The string to extract from |
start | Required. starting point. Can be a positive or negative number. If it is a positive number, this function extracts from the beginning of the string. If negative, this function extracts the |
#length | optional from the end of the string. The number of characters to extract. If omitted, the entire string (starting at position from ) |
Example: Use the SUBSTRING function to get the first 5 characters
mysql> SELECT SUBSTRING('MySQL SUBSTRING',1,5);
Method 2: Use the left() function
The LEFT() function is a string function that returns a string with a specified length left part.
LEFT(str,length);
The LEFT() function accepts two parameters:
str is the string from which the substring is to be extracted.
length is a positive integer specifying the number of characters to be returned from the left.
LEFT() function returns the leftmost length character in the str string. If the str or length parameter is NULL, a NULL value is returned.
If length is 0 or negative, the LEFT function returns an empty string. If length is greater than the length of the str string, the LEFT function returns the entire str string.
mysql> SELECT LEFT('MySQL LEFT', 5);
Method 3: Use the substr() function
SUBSTR() function to extract a substring from a string (from starting from any position).
SUBSTR(string, start, length)
Parameters | Description |
---|---|
string | Required item. The string to extract from |
start | Required. starting point. Can be a positive or negative number. If it is a positive number, this function extracts from the beginning of the string. If negative, this function extracts the |
#length | optional from the end of the string. The number of characters to extract. If omitted, the entire string will be returned (starting at the position) |
mysql video tutorial]
The above is the detailed content of How to get the first few digits of a string in mysql. For more information, please follow other related articles on the PHP Chinese website!