开发者

In mySQL, can you update a newly created table with fields from existing tables?

开发者 https://www.devze.com 2023-02-15 20:44 出处:网络
I am new to mySQL and would like some help with a query I\'m running. I\'d like to update a newly created table with fields from existing tables. Here is what I\'m working with.

I am new to mySQL and would like some help with a query I'm running. I'd like to update a newly created table with fields from existing tables. Here is what I'm working with.

UPDATE NEW_TABLE new, OLD_TABLE_1 one, OLD_TABLE_2 two, OLD_TABLE_3 three
SET
new.COLUMN_1 = one.COLUMN_1,
new.COLUMN_2 = one.COLUMN_2,
new.COLUMN_3 = one.COLUMN_3,
new.COLUMN_4 = two.COLUMN_1,
new.COLUMN_5 = two.COLUMN_2,
new.COLUMN_6 = three.COLUMN_1,
new.COLUMN_7 = three.COLUMN_2
WHERE
  three.COLUMN_1 = two.COLUMN_1 AND
  three.COLUMN_2 = one.COLUMN_1;

My data is all HR data. OLD_TABLE_1 is address information, OLD_TABLE_2 is medical information, and OLD_TABLE_3 is the original HR data. In the where clause, three.COLUMN_1 has a relationship with two.COLUMN_1. Imagine that three.COLUMN_1 is the user's ID and it maps to a user's ID in two.COLUMN_1. Also imagine that three.COLUMN_2 is a user's home phone number that maps to a user's home phone number in one.COLUMN_1. When the data is entered into the new table, I only want data for a unique individual. The reason for creating a new table is to optimize reporting. Drawing data from three tables is time consuming. I have large tables over 150GB in size. If I can load the data I need into a temp table, the query will run much quicker.

Any help would be greatl开发者_JAVA技巧y appreciated. Thanks in advance.


If this is a brand new table, you'd want to INSERT instead of UPDATE.

INSERT INTO NEW_TABLE
    (COLUMN_1, COLUMN_2, COLUMN_3, COLUMN_4, COLUMN_5, COLUMN_6, COLUMN_7)
    SELECT one.COLUMN_1, one.COLUMN_2, one.COLUMN_3, two.COLUMN_1, two.COLUMN_2, three.COLUMN_1, three.COLUMN_2
        FROM OLD_TABLE_1 one
            INNER JOIN OLD_TABLE_3 three
                ON one.COLUMN_1 = three.COLUMN_2
            INNER JOIN OLD_TABLE_2 two
                ON three.COLUMN_1 = two.COLUMN_1
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号