简体   繁体   中英

Update n rows from a table to n rows in another table (no foreign key)

I have 2 tables, table_1 and table_2 . table_1 included all data which I need to update to table_2 .

table_1

column_2 column_3
b1 b1
b2 b2

table_2

column_1 column_2 column_3 column_4
1 a1 a1 a
2 a a a
2 a a a
1 a2 a2 a
2 a a a

I need to put all data of table_1 to table_2 where column_1 is a specific number, for example, 1. However, I don't have any foreign key to join these two tables. The only relationship is that table_1 has n rows, table_2 also has n rows where column_1 = 1, and I want n rows in table_1 to be updated to these n rows in table_2 . My result would look like this:

column_1 column_2 column_3 column_4
1 b1 b1 a
2 a a a
2 a a a
1 b2 b2 a
2 a a a

Any help would be appreciated.

I think you should try to do that with a scripting language instead of using sql. get everything from table2 where column_1=1 order by column_2 to an array of objects like

[
 {column_1: 1, column_2: b1, column_3: b1, column_4: a},
 {column_1: 1, column_2: b2, column_3: b2, column_4: a}
]

then get everything from table1 order by column_2 in an array of objects

[
 {column_1: b1, column_2: b1},
 {column_1: b2, column_2: b2}
]

and for every element in table1, update table2 using column_1, column_2, column_3, column_4 in a where qlause

I dont think any other way to do this...it really a pain if the structure is like that

It's unclear by what logic you would like which rows in table1 to update which in table2. I will assume you just want to go in order: row 1 to row 1, 2 to 2 etc.

What we can do is add a row_number() to each table, then join on that.

I'm not 100% on MySQL syntax but hopefully you should get the idea. See also here for further "update through join" syntaxes:

WITH t2 AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
    FROM table_2
    WHERE column_1 = 1
),
t1 AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
    FROM table_1
)
UPDATE t2
SET
    t2.column_2 = t1.column_2,
    t2.column_3 = t1.column_3
INNER JOIN t1 ON t1.rn = t2.rn;

If you cannot do an update on a WITH table, then you must self-join table2 . You haven't indicated the PK of that table, I will just use column PK :

UPDATE table_2
SET
    table_2.column_2 = t1.column_2,
    table_2.column_3 = t1.column_3
INNER JOIN (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
    FROM table_2
    WHERE column_1 = 1
) AS t2 ON t2.PK = table_2.PK
INNER JOIN (
    SELECT *, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
    FROM table_1
)AS t1 ON t1.rn = t2.rn;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM