2011-04-25 44 views
2

拿到最後一個字我有類似下面的文字在我的數據庫mysql的SQL查詢文本

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

有substring_index()函數,但在你的情況下它不起作用,因爲你總是有不同的字符(空格,逗號,括號等)。我認爲你需要一些正則表達式,或者你必須使用大量的嵌套替換來刪除這些字符,然後再使用該函數。 – 2011-04-25 20:56:36

+0

我認爲只要讀取每一行並使用RegEx(或其他)來獲取代碼中的最後一個詞就會更好。 http://stackoverflow.com/questions/4380692/find-the-position-of-a-regex-substring-in-mysql – Compeek 2011-04-25 20:59:22

回答

3

這是一個例子:

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) 

正如你可以看到你將不得不使用大量的嵌套內容替換來完成你的任務。

+0

謝謝尼克你的幫助。這幫助我 – Bujji 2011-04-25 22:00:14

+0

很高興我可以幫忙;) – 2011-04-25 22:12:53

3

如果表是文本,與列ID和值

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

的性能可能會吸,如果你結束了幾個大型文本字段。可能想重新考慮這種方法。

+0

啊,沒有注意到你有多個分隔符:我的查詢將只工作,如果你正常化。或者用固定值替換所有分隔符或者(可能是最好的選擇)添加一列來存儲最後一個值,並在插入行時將其放在那裏。 – Femi 2011-04-25 21:10:35

+0

感謝Femi爲您的快速回應。我能夠得到預期的結果與尼克rulez查詢..再次感謝 – Bujji 2011-04-25 22:01:04