subquery? Update column in one table with value from another table

Posted on 2007-07-30
Last Modified: 2012-06-22
Using MySQL, I am trying to update one column in Table1 with the value from another column in  Table2. I guess I need a subquery, but I am not sure how to go about it.  Previously, there was not an autoincrement primary key in the Table2. Instead, the primarykey was derived from meta data. So, to fix this problem, I added an autoincrement primary key to each Table2 record. But now I have to update each Table1 record with the new primary key from Table2. The match can be the OLD primary key (the derived one), which is in both tables. Note, the old faux primary key is a VARCHAR, not an integer, if that matters.
Question by:aberns
    LVL 24

    Accepted Solution

    I think this is what you want. Just in case, it is always a good idea to back up your data first.

    update table1,table2
    set table1.key=table2.key
    where table1.oldkey=table2.oldkey
    LVL 2

    Expert Comment


    update T1
    set T1.key=T2.key
    FROM  table1 T1 Inner Join table2 T2 on T1.oldkey=T2.oldkey

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
    SQL Command Tool comes with APEX under SQL Workshop. It helps us to make changes on the database directly using a graphical user interface. This helps us writing any SQL/ PLSQL queries and execute it on the database and we can create any database ob…
    Video by: Steve
    Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    737 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    22 Experts available now in Live!

    Get 1:1 Help Now