通过触发器实现物化视图

2024-03-24 01:58
文章标签 实现 触发器 视图 物化

本文主要是介绍通过触发器实现物化视图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

        在电商平台中,我们有时需要对用户订单进行一些聚合计算,如订单总数有多少,总金额有多少,平均价格是多少,而实现这个特性基本有下面几个办法:

一, 每次查询这些聚合信息的时候,直接执行SQL语句的sum,avg,count等,好处是实现简单,不足是每次均需要进行扫表查询,特别是订单变更比较少,而查询比较多的情况下,此方法会浪费不少的机器资源。


二, 新建一个聚合表,当有订单增删改的时候,通过程序进行计算新的聚合信息,然后存储到该聚合表,每次查询的时候只需查询对应计算好的记录即可,好处是查询非常简单,不足是需要应用程序进行同步聚合信息,且如果订单库操作整个,而聚合库失败,则需要保证数据的一致性。


三,利用DB的触发器实现物化视图的方式,好处是数据的同步交给db 去保证,应用程序无需关注,并且若触发器执行失败,则对应的源表操作也会回滚,不足是需要开发对应的触发器程序。本文主要说明用触发器实现这样的一个特性,为了更好的说明如何创建的过程,我们举了这样一个例子,该例子已经在mysql全部调试通过。

     1, 新建一个订单表

            drop table orders if exists;

            create table orders (

                       order_id  int unsigned not null auto_increment,

                       product_name varchar(30) not null,

                       price  decimal(8,2) not null,

                       amount smallint not null,

                       primary key (order_id)

            )engine=innodb;


      2,创建一个存储聚合信息的表

           drop table orders_mv if exists;

           create table orders_mv (

                       product_name varchar(30) not null,

                       price_sum decimal(8,2) not null,

                       amount_sum int not null,

                       price_avg float not null,

                       orders_cnt int not null,

                       unique key product_name(product_name)  //因为需要按照产品名字聚合,这里把product_name作为唯一key进行去重

           ) engine=innodb;


      3,为表orders创建after insert的触发器

            首先说明一下如何查看一个表中是否已经创建了哪些触发器:           
            select * from information_schema.TRIGGERS where event_object_table='tbl_name'\G

            drop trigger tgr_orders_insert;


            delimiter $$
            create trigger tgr_orders_insert
            after insert on orders
            for each row
            begin
                   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)
                  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);

           end;
           $$
           delimiter ;


        4,为表orders创建after update的触发器

           drop trigger tgr_orders_update;

           delimiter $$
           create trigger tgr_orders_update
           after update on orders
           for each row
           begin     
                   if (STRCMP(OLD.product_name, NEW.product_name)) then        
                          update orders_mv
                          set
                          price_sum  = (price_sum  - OLD.price),
                          amount_sum = (amount_sum - OLD.amount),
                          orders_cnt = (orders_cnt - 1),
    
                          //错误,此时的price_sum已经是新值, 不能重新 -OLD.price + NEW.price
                          //price_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)
                         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          
                      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 ;





这篇关于通过触发器实现物化视图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/840170

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too