0

I have a table like this:

ID    Name      Email           Referred_by
-------------------------------------------
1     John      [email protected]    NULL
2     Sam       [email protected]     [email protected]
3     Sally     [email protected]   [email protected]
..... more rows .....

And I would like to change it to:

ID    Name      Email           Referred_by
-------------------------------------------
1     John      [email protected]    NULL
2     Sam       [email protected]     1
3     Sally     [email protected]   2
..... more rows .....

Can I make this change using SQL?

2 Answers 2

1

This should do the trick:

UPDATE my_table a
set    a.referred_by = (
       SELECT b.id
       FROM   my_table b
       WHERE  b.email = a.referred_by
);
Sign up to request clarification or add additional context in comments.

5 Comments

I think you have it the other way around.
Yeah I fixed it once I realised that :)
And once you do that you should change the datatype to integer so the old values cannot be inserted again.
mysql gives me: You can't specify target table 'a' for update in FROM clause
You didn't mention MySQL before - it has trouble with subqueries in UPDATE statements, especially if it's a self join. You need to create a temporary copy of the table (using ENGINE=MEMORY) and self join to that, without aliases (i.e. my_table_temp.email = my_table.referred_by).
1

Many DBMS' will allow this by the use of DDL (definition) statements rather than DML (manipulation). Assuming that id is an integral type and referred_by is (currently) a textual column, you can do something like:

  • alter the table to add a new column ref2 (nullable) of the same type as id.
  • set up a foreign key constraint between that ref2 and id.
  • populate the ref2 column for all the rows.
  • drop the original constraint.
  • alter the table to remove column referred_by.
  • alter the table to rename column ref2 to referred_by.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.