详解:
SUBSTRING(str, pos, length)函数截取特定长度的字符串,其中str为需截取的字符串,pos为截取起始位置,可以为负数,
为负数时表示从末尾第几位开始截取,length为截取长度。
例子:
mysql> select SUBSTRING('123AB5', 4, 2);
+---------------------------+
| SUBSTRING('123AB5', 4, 2) |
+---------------------------+
| AB |
+---------------------------+
1 row in set (0.00 sec)
mysql> select SUBSTRING('123AB5', -2, 2);
+----------------------------+
| SUBSTRING('123AB5', -2, 2) |
+----------------------------+
| B5 |
+----------------------------+
1 row in set (0.00 sec)
INSTR(str,substr)返回字符串“str”中子字符串的第一个出现位置。
例子:
mysql> select instr('121A25', '1');
+----------------------+
| instr('121A25', '1') |
+----------------------+
| 1 |
+----------------------+
1 row in set (0.00 sec)
LOCATE(substr,str) , LOCATE(substr,str,pos),第一个语法返回字符串 str中子字符串substr的第一个出现位置。
第二个语法返回字符串 str中子字符串substr的第一个出现位置, 起始位置在pos。如若substr 不在str中,则返回值为0。
例子:
mysql> select LOCATE('A', '12AB');
+---------------------+
| LOCATE('A', '12AB') |
+---------------------+
| 3 |
+---------------------+
1 row in set (0.00 sec)
mysql> select LOCATE('A', '12AB3AB', 5);
+---------------------------+
| LOCATE('A', '12AB3AB', 5) |
+---------------------------+
| 6 |
+---------------------------+
1 row in set (0.00 sec)
SUBSTRING()函数和INSTR()函数联合使用,例:
mysql> select SUBSTRING('12AB3a5AB190', INSTR('12AB3a5AB190', 'A'), 2);
+----------------------------------------------------------+
| SUBSTRING('12AB3a5AB190', INSTR('12AB3a5AB190', 'A'), 2) |
+----------------------------------------------------------+
| AB |
+----------------------------------------------------------+
1 row in set (0.00 sec)
注意:mysql中字符串下标从1开始。