开发者

Split values in a table with MySQL

I have the following table:

table Exemple
ID    Value
1 "word1-1,word2-1, word3-1, word4-2"
2 "word1-2,word2-2, word3-2, word4-3"
3 "word1-3,word2-3, word3-3, word4-4"
4 "word1-4,word2-4, word3-4,"
5 "word1-5,word2-5, word3-5, word4-6"
6 "word1-6,word2-6, , word4-7"

And I want to replace the value for each record with only the last word in the string (the words, if exist, are separated with commas). Note that sometime one word in the string is missing (line6), sometime all, and sometime only the last (line4). If the last word is missing I want to get a NULL value.

I.E. :

table Exemple
ID    Value
1 "word4-2"
2 "word4-3"
3 "word4-4"
4 NULL
5 "word4-6"
6 "word4-7"

I use MySQL.

Thank you开发者_运维技巧.


UPDATE  exemple
SET     value = NULLIF(TRIM(SUBSTRING_INDEX(value, ',', -1)), '')


Quite long winded but should give you what you need:

SELECT IF(LENGTH(SUBSTR(value,LENGTH(value) -(INSTR(REVERSE(value),",")-2)))>0, SUBSTR(value,LENGTH(value) -(INSTR(REVERSE(value),",")-2)), NULL) FROM Example
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜