mysql - 插入触发器后将数据插入另一个表

时间:2010-11-21 19:45:59

标签: mysql triggers insert

I have two tables - 

League        (lg_id, lg_Userid, lg_JoinDate)

此处,lg_id是PK并且其自动递增。

LeagueMember  (lgMbr_lg_id, lgMbr_Userid, lgMbr_JoinDate) 

lgMbr_lb_id是引用League(lg_id)

的FK

将一行插入League表后,应将相应的行插入到unionMember中,并将相同的lg_id插入到League表中。我正在尝试为此创建一个后插入触发器。

CREATE TRIGGER trigger_league AFTER INSERT ON `League` 
FOR EACH ROW 
BEGIN 
    INSERT INTO `LeagueMember` (`lgMbr_lg_id`, `lgMbr_Userid`,`lgMbr_JoinDate`) values (NEW.lg_id,NEW.lg_UserId,'2000-10-10')
END;

我尝试了这个,但它不起作用。这有什么不对吗?

编辑 -

我收到一条错误消息,说我的语法有错误。基于此mysql create trigger reference page我甚至试过了,但我仍然遇到语法错误。

CREATE TRIGGER trigger_league AFTER INSERT ON `League` 
FOR EACH ROW 
BEGIN 
    INSERT INTO `LeagueMember` SET lgMbr_lg_id = NEW.lg_id;    
END;

1 个答案:

答案 0 :(得分:3)

也许这可能会有所帮助???

drop table if exists league;
create table league
(
league_id smallint unsigned not null auto_increment primary key,
user_id int unsigned not null,
name varchar(255) unique not null
)
engine=innodb;

drop table if exists league_user;
create table league_user
(
league_id smallint unsigned not null,
user_id int unsigned not null,
created_date datetime not null,
creator_flag tinyint unsigned not null default 0,
primary key (league_id, user_id)
)
engine=innodb;


drop procedure if exists create_league;
delimiter #

create procedure create_league
(
in p_user_id int unsigned,
in p_name varchar(255)
)
begin

declare v_league_id smallint unsigned default 0;

    insert into league (user_id, name) values (p_user_id, p_name);

    set v_league_id = last_insert_id();

    call add_league_user(v_league_id, p_user_id, 1); -- 1 = owner
end #

delimiter ;

drop procedure if exists add_league_user;
delimiter #

create procedure add_league_user
(
in p_league_id smallint unsigned,
in p_user_id int unsigned,
in p_creator_flag tinyint unsigned
)
begin
    insert into league_user (league_id, user_id, created_date, creator_flag) values 
        (p_league_id, p_user_id, now(), p_creator_flag);
end #

delimiter ;

call create_league(1,'Premiere League');

call add_league_user(1,2,0);
call add_league_user(1,3,0);
call add_league_user(1,4,0);

select * from league;
select * from league_user;