Mysql – SQL UPDATE statement to update a column based on another existing row

MySQLsql

Basically I have a table that has similar format to the below table.

What I want to do is update Col4 based on this logic

  • if Col2 is null then update Col4 with Col3
  • if Col2 is not null then find the the value in Col1 which matches the value in Col2. update col4 with with the corresponding value in col3

For example given this table:

| Col1 | Col2 | Col3 | Col4 |
-----------------------------
|  1   |   2  |  A1  |  2   |
-----------------------------
|  2   |   3  |  A2  |  3   |
-----------------------------
|  3   |{null}|  A3  |{null}|

Update it to be this table

| Col1 | Col2 | Col3 | Col4 |
-----------------------------
|  1   |   2  |  A1  |  A2  |
-----------------------------
|  2   |   3  |  A2  |  A3  |
-----------------------------
|  3   |{null}|  A3  |  A3  |

Any direction would be greatly appreciated!

Best Answer

Something like this should work (untested):

UPDATE  table
SET     col4 = CASE WHEN table.col2 IS NULL THEN table.col3 ELSE col2Matches.col3 END
FROM    table
        INNER JOIN table AS col2Matches
            ON  table.col2 = col2Matches.col1

this should let you test it:

SELECT  CASE WHEN table.col2 IS NULL THEN table.col3 ELSE col2Matches.col3 END
FROM    table
        INNER JOIN table AS col2Matches
            ON  table.col2 = col2Matches.col1

Hope this helps,

Pete