如何获取 MySQL 中指定字符串中最后一个子字符串的索引?
如要获取指定字符串中最后一个子字符串的索引,请使用 char_length() 函数。首先,我们需要计算字符串长度,然后将最后一个子字符串长度从整个长度中减去。长度差即为子字符串索引。
语法
语法如下 −
select CHAR_LENGTH(yourColumnName) - LOCATE('yourDelimiter ', REVERSE(yourColumnName))+1 as anyVariableName from yourTableName;
为了理解上述语法,我们先创建一个表格。创建表格的查询如下 −
mysql> create table SubStringIndexDemo -> ( -> Words varchar(200) -> ); Query OK, 0 rows affected (0.57 sec)
使用 insert 命令在表格中插入一些记录。查询如下 −
mysql> insert into SubStringIndexDemo values('This is MySQL Query'); Query OK, 1 row affected (0.13 sec) mysql> insert into SubStringIndexDemo values('MySQL is a Relational Database'); Query OK, 1 row affected (0.34 sec) mysql> insert into SubStringIndexDemo values('Java is a programming language'); Query OK, 1 row affected (0.11 sec) mysql> insert into SubStringIndexDemo values('Spring is a Framework'); Query OK, 1 row affected (0.20 sec)
使用 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)
广告