MySQL根据另一个表的结果批量更新一个新表

时间:2019-10-10 12:55:16

标签: mysql sql database sql-update migration

我有一个相当复杂的数据库结构,有超过一百万条记录。我正在尝试将数据从现有实体迁移到新实体。

我正在迁移的旧数据表的结构如下:

MAIN / EXISTING TABLE

|-------|-----------|-----------|
| title | text      | parent_id |
|-------------------|-----------|
| HELLO | Something | 3001      |
|-------|-----------|-----------|
| HELLO | Hi!       | 3002      |
|-------|-----------|-----------|
| TEST  | World!    | 3001      |
|-------|-----------|-----------|

它有超过一百万条记录。

作为迁移目标的新表具有来自现有表的标题属性作为列名。

NEW TABLE

|---|-----------|-------|------|-------|
|id | parent_id | HELLO | TEST | OTHER |
|---|-----------|-------|------|-------|
| x | 3001      | NULL  | NULL | NULL  |
|---|-----------|-------|------|-------|
| y | 3002      | NULL  | NULL | NULL  |
|---|-----------|-------|------|-------|
| z | 3003      | NULL  | NULL | NULL  |
|---|-----------|-------|------|-------|

基于现有数据的新表的预期结果如下:

DESIRED NEW TABLE

|---|-----------|-----------|--------|-------|
|id | parent_id | HELLO     | TEST   | OTHER |
|---|-----------|-----------|--------|-------|
| x | 3001      | Something | World! | NULL  |
|---|-----------|-----------|--------|-------|
| y | 3002      | Hi!       | NULL   | NULL  |
|---|-----------|-----------|--------|-------|
| z | 3003      | NULL      | NULL   | NULL  |
|---|-----------|-----------|--------|-------|

可以像这样(伪代码)以编程方式实现结果:

FOREACH row IN `MAIN TABLE`:
    UPDATE `NEW TABLE` SET `row.title` = 'row.text'

但这不是可行的解决方案,因为有太多记录要循环。

有人知道该解决方案是否可以在MySQL中使用吗?

2 个答案:

答案 0 :(得分:1)

您可以在下面尝试-

    UPDATE NEWTABLE INNER JOIN
        (
           select max(case when title='HELLO' then text end) as hello,
           max(case when title='TEST' then text end) as test,
           max(case when title not in ('HELLO','TEST') then text end) as other
           from MAINTABLE group by parent_id
       )A ON NEWTABLE.parent_id= A.parent_id
       SET HELLO= A.hello,TEST=A.test,OTHER= A.other

答案 1 :(得分:1)

update newtab 
join maintab on maintab.parent_id=newtab.parent_id  set 
newtab.HELLO=if(maintab.title='HELLO',maintab.text,newtab.HELLO)
,newtab.TEST=if(maintab.title='TEST',maintab.text,newtab.TEST) 
,newtab.OTHER=if(maintab.title='OTHER',maintab.text,newtab.OTHER)

我认为您可以与此配合

相关问题