设为首页 加入收藏

TOP

通过触发器实现物化视图(二)
2014-11-24 00:59:55 来源: 作者: 【 】 浏览:15
Tags:通过 触发器 实现 物化
_avg = (price_sum - OLD.price) / IF((orders_cnt-1)>0, (orders_cnt-1), 1)
price_avg = price_sum /IF(orders_cnt>0, orders_cnt, 1)
where product_name = OLD.product_name;
set @old_price_sum = 0;
set @old_amount_sum = 0;
set @old_price_avg = 0;
set @old_orders_cnt = 0;
select IFNULL(price_sum, 0), IFNULL(amount_sum, 0), IFNULL(price_avg, 0), IFNULL(orders_cnt, 0) www.2cto.com
from orders_mv
where product_name = NEW.product_name
into @old_price_sum, @old_amount_sum, @old_price_avg, @old_orders_cnt;
set @new_price_sum = @old_price_sum + NEW.price;
set @new_amount_sum = @old_amount_sum + NEW.amount;
set @new_orders_cnt = @old_orders_cnt + 1;
set @new_price_avg = @new_price_sum / @new_orders_cnt;
replace into orders_mv
values (NEW.product_name, @new_price_sum, @new_amount_sum, @new_price_avg, @new_orders_cnt);
else
update orders_mv
set
price_sum = (price_sum - OLD.price + NEW.price),
amount_sum = (amount_sum - OLD.amount + NEW.amount),
//错误,此时的price_sum已经是新值, 不能重新 -OLD.price + NEW.price
//price_avg = (price_sum - OLD.price + NEW.price) /IF(orders_cnt>0,orders_cnt,1)
price_avg = price_sum /IF(orders_cnt>0,orders_cnt,1)
where product_name = OLD.product_name;
end if;
end;
$$
delimiter ;
5,为表orders创建after delete的触发器
drop trigger tgr_orders_delete;
delimiter $$
create trigger tgr_orders_delete
after delete on orders
for each row
begin www.2cto.com
update orders_mv
set
price_sum = (price_sum - OLD.price),
amount_sum = (amount_sum - OLD.amount),
orders_cnt = (orders_cnt - 1),
price_avg = price_sum /IF(orders_cnt>0, orders_cnt, 1)
where product_name = OLD.product_name;
end;
$$
delimiter ;
作者 tenfyguo
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇MySQL中隐藏空间问题浅析 下一篇MySQL中TIMESTAMPDIFF和TIMESTAMP..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: