获取 MySQL 中给定字符串中最后一个子字符串的索引?
要获取给定字符串中最后一个子字符串的索引,请使用该char_length()函数。首先,我们需要计算字符串长度并从整个长度中减去最后一个子字符串长度。长度的差异是子串的索引。
语法
语法如下 -
select CHAR_LENGTH(yourColumnName) - LOCATE('yourDelimiter ',REVERSE(yourColumnName))+1 as anyVariableName
from yourTableName;
要理解上述语法,让我们首先创建一个表。创建表的查询如下 -
mysql> create table SubStringIndexDemo-> (
-> Words varchar(200)
-> );
使用插入命令在表中插入一些记录。查询如下 -
mysql> insert into SubStringIndexDemo values('This is MySQL Query');mysql> insert into SubStringIndexDemo values('MySQL is a Relational Database');
mysql> insert into SubStringIndexDemo values('Java is a programming language');
mysql> insert into SubStringIndexDemo values('Spring is a Framework');
使用 select 命令显示表中的所有记录。查询如下 -
mysql> select *from SubStringIndexDemo;输出结果
+--------------------------------+| Words |
+--------------------------------+
| This is MySQL Query |
| MySQL is a Relational Database |
| Java is a programming language |
| Spring is a Framework |
+--------------------------------+
4 rows in set (0.00 sec)
这是可用于获取最后一个子字符串索引的查询:
mysql> select CHAR_LENGTH(Words) - LOCATE(' ', REVERSE(Words))+1 as输出结果PositionOfLastSubstring
-> from SubStringIndexDemo;
+-------------------------+| PositionOfLastSubstring |
+-------------------------+
| 14 |
| 22 |
| 22 |
| 12 |
+-------------------------+
4 rows in set (0.00 sec)
以上是 获取 MySQL 中给定字符串中最后一个子字符串的索引? 的全部内容, 来源链接: utcz.com/z/331856.html