Reputation: 155
I have table :
id | f_name | m_name | l_name
1 | a b c | null | null
2 | a b c | null | null
3 | a b c | null | null
i want output like this :
id | f_name | m_name | l_name
1 | a | b | c
2 | a | b | c
3 | a | b | c
My select query works and the data output is like that. I am having challenges updating multiple columns at the same time. Any advise or useful links will be appreciated.
My query:
update tbl_client_test1 set f_name, m_name, l_name = (SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(f_name, ' ', 1), ' ', -1) AS f_name,
If( length(f_name) - length(replace(f_name, ' ', ''))>1,
SUBSTRING_INDEX(SUBSTRING_INDEX(f_name, ' ', 2), ' ', -1) ,NULL)
as m_name,
SUBSTRING_INDEX(SUBSTRING_INDEX(f_name, ' ', 3), ' ', -1) AS l_name
FROM tbl_client_test1)
Upvotes: 1
Views: 481
Reputation: 164079
For this sample data, this will work:
UPDATE tbl_client_test1
SET m_name = CASE
WHEN CHAR_LENGTH(f_name) - CHAR_LENGTH(REPLACE(f_name, ' ', '')) > 0
THEN SUBSTRING_INDEX(SUBSTRING_INDEX(f_name, ' ', 2), ' ', -1)
END,
l_name = CASE
WHEN CHAR_LENGTH(f_name) - CHAR_LENGTH(REPLACE(f_name, ' ', '')) > 1
THEN SUBSTRING_INDEX(f_name, ' ', -1)
END,
f_name = SUBSTRING_INDEX(f_name, ' ', 1);
Note that f_name
is updated last in the statement, because it is used in the expressions that update the other 2 columns.
See the demo.
Upvotes: 1
Reputation: 381
While I agree with the comment of Tim Biegeleisen, I also know you don't always have a say in how data comes your way. So in that case I would solve it like this:
SELECT
REGEXP_SUBSTR(s.test, '[a-z]+', 1, 1) AS field1,
REGEXP_SUBSTR(s.test, '[a-z]+', 1, 2) AS field2,
REGEXP_SUBSTR(s.test, '[a-z]+', 1, 3) AS field3,
REGEXP_SUBSTR(s.test, '[a-z]+', 1, 4) AS field4,
REGEXP_SUBSTR(s.test, '[a-z]+', 1, 5) AS field5
FROM
(SELECT 'aaaa bbbbb cc ddddd eee f ggggg hh ii jj' AS test) AS s
Works with different string lengths, but you might need to tweak the regular expression if the 'a b c' values in your example have a different format.
The last parameter is the nth occurrence of the regexp. See docs.
Upvotes: 1