如何创建mysql触发器来更新列

时间:2015-03-10 10:13:09

标签: mysql database triggers

我想根据另一个表中设置的值更新新插入行的列。

我创造了这样的东西:

BEGIN
DECLARE value float;
DECLARE comission float;    
DECLARE c float;

select value=`uc_amount` from inserted;

select comission=`config_value` from fixed_configs WHERE `config_key` = 'deal_comission';

c = value - (value * (comission/100));

update user_credits set `uc_admin_amount`=value;

END

但它显示错误

这里的表结构

user_credit:

uc_amount   float(10,2) 
uc_admin_amount float(5,2)
uc_created  timestamp
uc_extra    text

fixed_configs:

config_key varchar(225)  config_value varchar(225)

1 个答案:

答案 0 :(得分:1)

您基本上需要两个触发器before insert和一个before update

之前的插入内容会获得uc_amount并计算uc_admin_amount,而before update会检查旧的uc_amount是否与新的uc_amount不同,如果是这样的话。

delimiter //

create trigger ins_user_credit before insert on user_credit
for each row
begin
 declare comission float(5,2);
 select config_value into comission from fixed_configs WHERE config_key = 'deal_comission';
 set new.uc_admin_amount = new.uc_amount - (new.uc_amount * (comission/100));
end; //

delimiter ;


delimiter //

create trigger upd_user_credit before update on user_credit
for each row
begin
 declare comission float(5,2);
 if(old.uc_amount <> new.uc_amount)
   select config_value into comission from fixed_configs WHERE config_key = 'deal_comission';
   set new.uc_admin_amount = new.uc_amount - (new.uc_amount * (comission/100));
 end if ;
end; //

delimiter ;