0

我有 2 个具有一对多关系的表,我需要以下插入:

A - source table
nr  Name
1   a
1   b
1   c
2   d
2   e
546 abc
546 asd
546 qwe

B - results table
FK_ID Name
...
6     a
6     b
6     c
7     d
7     e
8     abc
8     asd
8     qwe

C - table with unique IDs
ID
...
5 
6 (new)
7 (new)
8 (new)

我从源表中取出行,将它们插入结果表中,对于每个组,我需要在表中插入具有唯一 ID的行并更新结果表中插入的行,因此我在 B 和 C 之间有关系(ID 是在 C 中自动递增)。

我应该做一个 BEFORE/AFTER INSERT 触发器,还是有更快的方法?(> 100k 行)

编辑:

我从 B 中删除了外键,所以我可以在 B 中插入任何内容,但现在第 2 步需要太多时间(3k 行/10 分钟)。

-- step 1
insert into B(..., helperColumn)
select ..., 1 from A;


-- step 2
myloop: WHILE true DO
    set @updateID = (select ID from B where helperColumn = 1 limit 1);
    if @updateID is null then
        LEAVE myloop;
    end if;

    insert into C(...)
    values(...);

    set @id = LAST_INSERT_ID();

    update B
    set ID = @id, helperColumn = 0
    where ID = @updateID
    and helperColumn = 1;

END WHILE;
4

1 回答 1

0

我的最终解决方案是:

insert into B(FK_ID, ...)
select InsertC(nr), ... from A;

InsertC 是一个函数

CREATE FUNCTION `InsertC`(pOldID BIGINT) RETURNS bigint(20)
BEGIN

    set @newID = (select ID from B where OldID = pOldID);

    if @newID is null then
        insert into C(..., OldID)
        values(..., pOldID);

        set @newID = LAST_INSERT_ID();
    end if;

    RETURN @newID;
END

我仍然需要 B 中的新列(OldID + 索引),但这比以前快得多。

于 2013-03-08T08:28:20.607 回答