简体   繁体   English

mySQL 将值拆分为多行

[英]mySQL split values to multiple rows

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) 

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.虽然我同意 Tim Biegeleisen 的评论,但我也知道您并不总是对数据如何以您的方式发表意见。 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 'abc' values in your example have a different format.适用于不同的字符串长度,但如果示例中的 'abc' 值具有不同的格式,则可能需要调整正则表达式。

The last parameter is the nth occurrence of the regexp.最后一个参数是正则表达式的第 n 次出现。 See docs .请参阅文档

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.请注意, f_name在语句中最后更新,因为它用于更新其他 2 列的表达式。

See the demo .请参阅演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM