0

我在 MySQL 中使用触发器来执行以下操作:

当我将新客户端添加到客户端表时,它应该在“客户端类型”表中创建一组条目,将客户端 ID 链接到一组类型 ID(client1、type1 client1、type2)等...

但是,当触发器运行时,数据库会两次插入最后一种类型的条目。所以最后两个条目是(client1,type9 client1,type9)。

触发代码如下:

AFTER INSERT ON `nmsTicket`.`client`
FOR EACH ROW
BEGIN

   DECLARE done BOOLEAN DEFAULT 0;
   DECLARE a CHAR(2);

   DECLARE types CURSOR
   FOR
   SELECT typeID FROM type;

   DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

   OPEN types;


 REPEAT
      FETCH types INTO a;



       INSERT INTO clientType(id_type, id_client) VALUES (a,new.idClient);

   UNTIL done END REPEAT;

   CLOSE types;

我已经看过几次了,但我不明白为什么它会表现出这种行为;最后一个之前的所有条目都可以正常工作。

任何指针?

4

1 回答 1

0

我不确定您为什么在触发器中使用游标 - 除非您绝对需要,否则应该避免这种情况(请参阅此处,例如Optimal MySQL settings for queries that deliver大量数据?

下面是一个使用交叉连接而不是游标的简化示例(减去参照完整性)。此外,您会注意到我没有在 client_types 表上使用代理主键,而是使用复合主键来更好地执行数据完整性。

架构

drop table if exists client_type; --your type table
create table client_type
(
type_id tinyint unsigned not null auto_increment primary key,
name varchar(255) unique not null
)
engine=innodb;

drop table if exists client;
create table client
(
client_id int unsigned not null auto_increment primary key,
name varchar(255) not null
)
engine=innodb;

drop table if exists client_types; -- your clienttype table
create table client_types
(
client_id int unsigned not null,
type_id tinyint unsigned not null,
primary key (client_id, type_id) -- ** note use of composite primary key **
)
engine=innodb;

delimiter #

create trigger client_after_ins_trig after insert on client
for each row
begin

insert into client_types (client_id, type_id) 
select
 c.client_id,
 ct.type_id
from
 client c
cross join client_type ct
where
 c.client_id = new.client_id
order by
 ct.type_id;

end#

delimiter ;

测试

mysql> insert into client_type (name) values ('type one'),('type two'),('type three');
Query OK, 3 rows affected (0.03 sec)

mysql> insert into client (name) values ('client A'),('client B');
Query OK, 2 rows affected (0.04 sec)

mysql> select * from client_type;
+---------+------------+
| type_id | name       |
+---------+------------+
|       1 | type one   |
|       3 | type three |
|       2 | type two   |
+---------+------------+
3 rows in set (0.00 sec)

mysql> select * from client;
+-----------+----------+
| client_id | name     |
+-----------+----------+
|         1 | client A |
|         2 | client B |
+-----------+----------+
2 rows in set (0.00 sec)

mysql> select * from client_types;
+-----------+---------+
| client_id | type_id |
+-----------+---------+
|         1 |       1 |
|         1 |       2 |
|         1 |       3 |
|         2 |       1 |
|         2 |       2 |
|         2 |       3 |
+-----------+---------+
6 rows in set (0.00 sec)

希望这可以帮助 :)

于 2012-04-12T09:41:38.780 回答