MySQL查询从字段中提取最后一个字?
要从字段中提取最后一个单词,请使用内置的SUBSTRING_INDEX()函数。语法如下-
SELECT SUBSTRING_INDEX(yourColumnName,’ ‘,-1) as anyVariableName from yourTableName;
为了理解上述概念,让我们创建一个表。以下是创建表的查询-
mysql> create table FirstWordDemo −> ( −> AllWords longtext −> );
现在,使用插入命令在表中插入一些单词。查询如下-
mysql> insert into FirstWordDemo values('This is the first MySQL Query'); mysql> insert into FirstWordDemo values('MySQL is a Relational Database'); mysql> insert into FirstWordDemo values('FirstWord is not correct');
现在,使用select语句显示表中的所有记录。查询如下-
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)