我不确定您为什么在触发器中使用游标 - 除非您绝对需要,否则应该避免这种情况(请参阅此处,例如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)
希望这可以帮助 :)