MySql update with subselect

2019-08-18 17:38发布

I have a mysql database table where there is an email column which can contain up to two emails separated by an semicolon. What i want to achieve is write the second email address in the email field into another column email2 This is what I tried so far without success:

UPDATE user AS u
SET email2 = (SELECT SUBSTRING_INDEX(email, ';', -1)
              FROM user
              WHERE user.id=u.id)
WHERE username LIKE "%;%"

When searching for this problems there were some solutions unsing a second subquery within the subquery but none of them really matched my problem.

If anybody has a solution please post it. I have been stuck for at leas 2 hours.

Thank you very much.

1条回答
孤傲高冷的网名
2楼-- · 2019-08-18 18:24

No need to complicate your life :

UPDATE user 
SET email2 = SUBSTRING_INDEX(email, ';', -1) 
WHERE username LIKE '%;%';

and to clean first column in same query

UPDATE user 
SET 
  email2 = SUBSTRING_INDEX(email, ';', -1),
  email = SUBSTRING_INDEX(email, ';', 1),
WHERE username LIKE '%;%';
查看更多
登录 后发表回答