将名字拆分为名字和姓氏并插入现有的名字列和姓氏列 sql

Split names into first and last and insert into existing first Name column and last Name column sql

我有一个 table,其中有一列名为 CustomerName,其中包含名字、中间名首字母和姓氏。有些名字可能没有中间名首字母。在同一个 table 中,我有 3 个名为 firstNamemiddleNameLastName 的列,其中填充了 None 值。我需要拆分 CustomerName 列并将它们放在各自的列中。我将如何在 mysql 中做到这一点?我尝试了以下但出现错误:

UPDATE xcust SET
LastName = SUBSTRING_INDEX(trim(CustomerName),' ',-1) 
case 
when LENGTH(trim(CustomerName)) - LENGTH(REPLACE(trim(CustomerName), ' ', 
'')) = 1 then null
else  MiddleName = SUBSTRING_INDEX(SUBSTRING_INDEX(trim(CustomerName),' 
',2),' ',-1) 
end
FirstName = SUBSTRING_INDEX(trim(CustomerName),' ',1)
where CustomerName = 'JAMES G STAHL'"""

我收到的错误是:

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'case \nwhen LENGTH(trim(CustomerName)) - LENGTH(REPLACE(trim(CustomerName), ' ', ' at line 3")

我正在使用 pymysql 运行 查询。任何帮助,将不胜感激。

未测试,但乍一看您正在设置的不同值之间缺少逗号,需要在 case 语句之外使用 MiddleName。

UPDATE xcust SET
LastName = SUBSTRING_INDEX(trim(CustomerName),' ',-1),
MiddleName = 
    case when LENGTH(trim(CustomerName)) - LENGTH(REPLACE(trim(CustomerName), ' ', '')) = 1 then
        null
    else
        SUBSTRING_INDEX(SUBSTRING_INDEX(trim(CustomerName),' ',2),' ',-1)
    end,
FirstName = SUBSTRING_INDEX(trim(CustomerName),' ',1)
where CustomerName = 'JAMES G STAHL'