Mysql SQL查询获取文本中的最后一个单词

时间:2011-04-25 20:53:12

标签: mysql string substring

我的数据库中有类似下面的文字

this is my car
how are you,doing
how is your)health
this is not(working

当我查询数据库时,我应该从这个文本中得到最后的单词。在这个例子中

1st row should return "car"
2nd row should return "doing"
3rd row should return "health"
4th row should return "working"

关于如何获得这个的任何想法?

感谢您的帮助

此致

基兰

2 个答案:

答案 0 :(得分:4)

这是一个例子:

create table lastword (
id int not null auto_increment primary key,
mytext varchar(250)
) engine = myisam;

insert into lastword (mytext) values 
('this is my car'),
('how are you,doing'),
('how is your)health'),
('this is not(working');

select *,
substring_index(replace(replace(replace(mytext,',',' '),')',' '),'(',' '),' ',-1) as last 
from lastword

+----+---------------------+---------+
| id | mytext              | last    |
+----+---------------------+---------+
|  1 | this is my car      | car     |
|  2 | how are you,doing   | doing   |
|  3 | how is your)health  | health  |
|  4 | this is not(working | working |
+----+---------------------+---------+
4 rows in set (0.00 sec)

如您所见,您必须使用大量嵌套替换来完成任务。

答案 1 :(得分:3)

如果表格是文本,则列ID和VALUE

select ID, RIGHT(VALUE, LOCATE(' ', REVERSE(VALUE))) FROM text;

如果您最终得到几个大文本字段,性能可能会很糟糕。可能想重新考虑这种方法。