我的触发器插入许多记录

my trigger inserts way to many records

我有以下触发器:

    begin
 insert into user_has_competence (user_id,competence_id)
 select u.id,c.id from competence c
 join user u on u.organization_id = c.organization_id and c.organization_id = new.organization_id;
end

涉及的表格如下:

    Table: competence
Columns:
id  int(11) AI PK
name    varchar(400)
organization_id int(11)
competence_type_id  int(11)
competence_category_id  int(11)


Table: user
Columns:
id  int(11) AI PK
username    varchar(100)
password    varchar(100)
is_active   int(11)
user_type_id    int(11)
token   varchar(445)
organization_id int(11)
title_id    int(11)
image_path  varchar(100)
division_id int(11)

    Table: user_has_competence
Columns:
user_id int(11) PK
competence_id   int(11) PK
competence_level_id int(11)
progression varchar(45)
id  int(11) AI PK

现在我有 8 个用户,当我插入 64 个 competence 时,我最终将超过 30k 行插入 user_has_competence

谁能告诉我为什么会这样?

更准确地说,它插入了 626433 行。

总之……一个猜想……

您有插入到 user_has_competence 时的触发器,当插入一行时,它会去插入更多行到同一个 table,触发该触发器的另一个实例。这一直在继续。直到你 运行 出 space。 (这可以解释为什么您看到了 30k 行然后是 626k 行;现在更多了吗?)

并且由于您在 user_has_competence 上的主键是自动递增的,因此它不会阻止您插入重复的行 ...

一个用户似乎在每个组织中只能拥有一个权限?如果是这样,我建议在 user_id, competence_id, organisation_id in user_has_competence table 上进行复合 PK。 (您需要在此处添加 organisation_id )。然后,当您的触发器尝试插入重复值时,您会看到错误

编辑:部分问题可能是您的触发器不包含您刚刚插入的新 competence_id 的 where 子句,因此它将为所有现有的用户能力关系添加重复项