开发者

Split values in a table with MySQL

开发者 https://www.devze.com 2023-03-03 03:45 出处:网络
I have the following table: table Exemple IDValue 1 \"word1-1,word2-1, word3-1, word4-2\" 2 \"word1-2,word2-2, word3-2, word4-3\"

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

精彩评论

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