How to replace value in mysql column by query like, Column is options
and its of type varchar(255)
From
id options
1 A
Demo
Rextester demo
Explanation
This could be solved relatively easily if only MySQL had a regular expression replacement function but unfortunately it doesn't. So I wrote one - see this blog post. The "advanced version" is needed here to allows it to perform a recursive replace in the found match for the replacement. Then the following relatively simple SQL can be used:
SQL (function code omitted for brevity)
SELECT id,
options AS `before`,
reg_replace(options,
'\\|.*\\|', -- 2 pipe symbols with any text in between
'\\|$', -- Replace the second pipe symbol
',', -- Replace with a comma
FALSE, -- Non-greedy matching
2, -- Min match length = 2 (2 pipe symbols)
0, -- No max match length
0, -- Min sub-match length = 1 (1 pipe symbol)
0 -- Max sub-match length = 1 (1 pipe symbol)
) AS `after`
FROM tbl;