用于从字段中提取最后单词的 MySQL 查询?
要从字段中提取最后一个单词,请使用内置的 SUBSTRING_INDEX() 函数。语法如下 −
SELECT SUBSTRING_INDEX(yourColumnName,’ ‘,-1) as anyVariableName from yourTableName;
为了理解上述概念,让我们创建一个表。以下是用于创建表的查询 −
mysql> create table FirstWordDemo −> ( −> AllWords longtext −> ); Query OK, 0 rows affected (0.83 sec)
现在,使用插入命令在表中插入一些单词。查询如下 −
mysql> insert into FirstWordDemo values('This is the first MySQL Query'); Query OK, 1 row affected (0.11 sec) mysql> insert into FirstWordDemo values('MySQL is a Relational Database'); Query OK, 1 row affected (0.17 sec) mysql> insert into FirstWordDemo values('FirstWord is not correct'); Query OK, 1 row affected (0.21 sec)
现在,使用选择语句显示表中的所有记录。查询如下 −
mysql> select *from FirstWordDemo;
以下是输出 −
+--------------------------------+ | AllWords | +--------------------------------+ | This is the first MySQL Query | | MySQL is a Relational Database | | FirstWord is not correct | +--------------------------------+ 3 rows in set (0.00 sec)
以下是显示字段中最后一个单词的查询。我们在开始时讨论了相同的语法。以下是查询 −
mysql> select SUBSTRING_INDEX(AllWords, ' ', -1) as MyFirstWordResult from FirstWordDemo;
以下是输出 −
+-------------------+ | MyFirstWordResult | +-------------------+ | Query | | Database | | correct | +-------------------+ 3 rows in set (0.00 sec)
广告