MySql update with subselect

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 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.

Answer #1:

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 
  email2 = SUBSTRING_INDEX(email, ';', -1),
  email = SUBSTRING_INDEX(email, ';', 1),
WHERE username LIKE '%;%';
Answered By: Raphaƫl Althaus
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

# More Articles