[英]Select part of value in one column and copy it to another column - sql query
I have the following sql query that needs to be fixed to trim any whitespace (beginning and end) of the selection.我有以下 sql 查询需要修复以修剪选择的任何空白(开头和结尾)。 I also need it to delete the "lastname" part from the firstname column:
我还需要它从 firstname 列中删除“lastname”部分:
UPDATE customer_address_entity
SET lastname = RIGHT(firstname,LENGTH(firstname)-LOCATE(' ',firstname))
WHERE lastname = ''
For instance if the column "firstname" has "Jo de blog " in it and "lastname" column is empty I want the "firstname" column to contain "Jo" and the "lastname" column to contain "de Blog"例如,如果“firstname”列中包含“Jo de blog”并且“lastname”列为空,我希望“firstname”列包含“Jo”,“lastname”列包含“de Blog”
I would apporach it so.我会这样对待它。
When the firstname has 2 surnames it would take the last two When the firstname has 1 surnames it would take also only the last With increasing number of words in firstname.当名字有 2 个姓氏时,它会取最后两个当名字有 1 个姓氏时,它也只会取最后一个名字,名字中的单词数量越来越多。 you need a more sophisticated algorithm to find the right index
您需要更复杂的算法来找到正确的索引
CREATE TABLE customer_address_entity ( `id`INT, `firstname` varchar(25), `lastname` varchar(25) ); INSERT INTO customer_address_entity (`id`,`firstname`, `lastname`) VALUES (1,'Jo de blog ',''),(2,'Jo blog ',''),(3,'test2','test2');
SELECT * FROM customer_address_entity
id |编号 | firstname |
名字 | lastname -: |:---------- |:------- 1 |
姓氏 -: |:--------- |:-------- 1 | Jo de blog |
乔德博客 | 2 |
2 | Jo blog |
乔博客 | 3 |
3 | test2 |
测试2 | test2
测试2
UPDATE `customer_address_entity` SET `lastname` = TRIM(SUBSTRING_INDEX(TRIM(`firstname`), " ", IF(LENGTH(TRIM(`firstname`)) - LENGTH(REPLACE(TRIM(`firstname`), ' ', '')) > 1,-2,-1))), firstname = TRIM(SUBSTRING_INDEX(TRIM(`firstname`), " ", 1)) WHERE `lastname` = '';
SELECT * FROM customer_address_entity
id |编号 | firstname |
名字 | lastname -: |:-------- |:------- 1 |
姓氏 -: |:-------- |:-------- 1 | Jo |
乔 | de blog 2 |
博客 2 | Jo |
乔 | blog 3 |
博客 3 | test2 |
测试2 | test2
测试2
This is a bit tricky, because your expression would not produce the expected results if the string starts with a space.这有点棘手,因为如果字符串以空格开头,您的表达式将不会产生预期的结果。
I would use:我会使用:
substring(trim(firstname), locate(' ', trim(firstname)) + 1)
This basically starts by removing leading and trailing spaces from the string, then selects everything after the first space within the string.这基本上首先从字符串中删除前导和尾随空格,然后选择字符串中第一个空格之后的所有内容。
In your update
statement:在您的
update
声明中:
UPDATE `customer_address_entity`
SET `lastname` = substring(trim(firstname), locate(' ', trim(firstname)) + 1)
WHERE `lastname` = ''
If there may be multiple spaces between the first name and last name, then you can trim()
the resulting string too:如果名字和姓氏之间可能有多个空格,那么您也可以
trim()
结果字符串:
trim(substring(trim(firstname), locate(' ', trim(firstname)) + 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.