使用触发器使用其他表值更新值

时间:2016-04-26 17:48:22

标签: mysql sql triggers

我有两张桌子!

PID

 P        ID
Jo Te     00001
Mo To     00002
Tim Fo    00003

NF0

 P2        NewID       Team
Jo Te         -       TeamC
Mo To         -       TeamV
Jo Te         -       TeamX
Tim Fo        -       TeamZ

如果在表PID中插入新值,我想创建一个更新表NF0的触发器!我写了这个触发器upd:

delimiter $$
Create trigger upd after insert on pid
 for each row begin
update nf0 set nf0.PID=new.iD ;
 end $$

,但它会像这样更新它!

NF0

 P2         NewID       Team
Jo Te      00003       TeamC
Mo To      00003       TeamV
Jo Te      00003       TeamX
Tim Fo        -        TeamZ

,但我希望输出看起来像这样

  P2        NewID       Team
Jo Te      00001       TeamC
Mo To      00002       TeamV
Jo Te      00001       TeamX
Tim Fo     00003       TeamZ

我写错了什么?

2 个答案:

答案 0 :(得分:1)

这有效:

create table PID (
    P  char(10),
    ID char(10)
);

create table nf0 (
    P2    char(10),
    NewID char(10),
    Team  char(10)
);

insert into nf0 (P2,Team) values
    ('Jo Te',  'TeamC'),    
    ('Mo To',  'TeamV'),    
    ('Jo Te',  'TeamX'),    
    ('Tim Fo', 'TeamZ');

delimiter $$
create trigger upd after insert on PID
for each row
begin
    update nf0 set NewID=new.ID where P2=new.P;
end $$
delimiter ;

select * from nf0;

+--------+-------+-------+
| P2     | NewID | Team  |
+--------+-------+-------+
| Jo Te  | NULL  | TeamC |
| Mo To  | NULL  | TeamV |
| Jo Te  | NULL  | TeamX |
| Tim Fo | NULL  | TeamZ |
+--------+-------+-------+
4 rows in set (0.01 sec)

insert into PID (P,ID) values
    ('Jo Te',  '00001'),
    ('Mo To',  '00002'),
    ('Tim Fo', '00003');

select * from nf0;

+--------+-------+-------+
| P2     | NewID | Team  |
+--------+-------+-------+
| Jo Te  | 00001 | TeamC |
| Mo To  | 00002 | TeamV |
| Jo Te  | 00001 | TeamX |
| Tim Fo | 00003 | TeamZ |
+--------+-------+-------+
4 rows in set (0.00 sec)

从OP的评论中可以清楚地看到表PID被另一个触发器填充。因此,触发器upd必须在之后调用其他触发器。我们假设另一个触发器被称为fill_pid,然后是

delimiter $$
create trigger upd after insert on PID 
for each row FOLLOWS fill_pid
begin
    update nf0 set NewID=new.ID where P2=new.P;
end $$
delimiter ;

会做的。

答案 1 :(得分:0)

delimiter $$
Create trigger upd after insert on pid
 for each row begin
update nf0 set nf0.P2=new.iD 
where nf0.P2 = new.P;
 end $$