插入相关表格

时间:2013-03-04 14:43:10

标签: mysql triggers relational-database

我有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;

1 个答案:

答案 0 :(得分: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 + index),但这比以前快得多。