Mysql 使用临时表中的值更新表中的多行

Mysql 使用临时表中的值更新表中的多行,mysql,Mysql,我试图编写一个数据库迁移脚本,将一列添加到包含现有数据的表中,然后用适当的数据填充该列 我将分几个步骤进行迁移。我创建了一个临时表,其中包含一个ID如下的列: new_column ========== 1000 1001 1002 1003 ... old_column_1 | old_column_2 | new_column ======================================== 1 | 100 | null 2

我试图编写一个数据库迁移脚本,将一列添加到包含现有数据的表中,然后用适当的数据填充该列

我将分几个步骤进行迁移。我创建了一个临时表,其中包含一个ID如下的列:

new_column
==========
1000
1001
1002
1003
...  
old_column_1 | old_column_2 | new_column
========================================
1            | 100          | null
2            | 101          | null
3            | 102          | null
...
现在我想更新我的现有表,以便上面临时表中的每一行都用于更新我现有表中的每一行。现有表如下所示:

new_column
==========
1000
1001
1002
1003
...  
old_column_1 | old_column_2 | new_column
========================================
1            | 100          | null
2            | 101          | null
3            | 102          | null
...
我尝试过这种更新的一些变体-

select min(t.new_column) 
from temp t 
where t.new_column not in (select new_column from existing_table);

但是我似乎无法正确理解语法…

你的问题比你想象的要复杂。没有什么可靠的东西可以加入。因此,要么编写一个存储过程,使用游标在两个表中循环,并逐行更新现有表(这很快会成为性能噩梦,因此我不推荐这样做),要么使用这个稍微复杂的查询:

CREATE TABLE temp
    (id int auto_increment primary key, `new_column` int)
;

INSERT INTO temp
    (`new_column`)
VALUES
    (1000),
    (1001),
    (1002),
    (1003)
;



CREATE TABLE existing
    (`old_column_1` int, `old_column_2` int, `new_column` varchar(4))
;

INSERT INTO existing
    (`old_column_1`, `old_column_2`, `new_column`)
VALUES
    (1, 100, NULL),
    (2, 101, NULL),
    (3, 102, NULL)
;

update 
existing e 
inner join (
  select * from (
    select
    t.*
    from temp t
  )t
  inner join
  (
    select
    e.old_column_1, e.old_column_2,
    @rownum := @rownum + 1 as rn
    from existing e
    , (select @rownum:=0) vars
  )e on t.id = e.rn
) sq on sq.old_column_1 = e.old_column_1 and sq.old_column_2 = e.old_column_2
set e.new_column = sq.new_column;
  • 现场观看它的工作
我在临时表中添加了一个自动增量列。要么这样做,要么像我在这里做的那样模拟行数:

    select
    e.old_column_1, e.old_column_2,
    @rownum := @rownum + 1 as rn
    from existing e
    , (select @rownum:=0) vars
如果您想影响哪一行获得哪一行号,可以使用
ORDER BY_column ASC | DESC


因此,查询的基本功能是在现有表中创建一个行号,并通过此列和临时表中的自动增量列将其连接起来。然后我将这个子查询再次连接到现有表,这样我们就可以轻松地将临时表中的列复制到现有表中。

请解释应该将临时表中的哪个值分配给旧表中的哪一行?为什么查询使用
min
函数?@rcgeorge23有任何反馈吗?您好@fancypants-感谢您的回复并对延迟表示歉意!我被另一个项目拖了几天,但今天下午我要尝试一下。