通过触发器实现物化视图

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

相关文章

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

PostgreSQL中MVCC 机制的实现

《PostgreSQL中MVCC机制的实现》本文主要介绍了PostgreSQL中MVCC机制的实现,通过多版本数据存储、快照隔离和事务ID管理实现高并发读写,具有一定的参考价值,感兴趣的可以了解一下... 目录一 MVCC 基本原理python1.1 MVCC 核心概念1.2 与传统锁机制对比二 Postg

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

C++中零拷贝的多种实现方式

《C++中零拷贝的多种实现方式》本文主要介绍了C++中零拷贝的实现示例,旨在在减少数据在内存中的不必要复制,从而提高程序性能、降低内存使用并减少CPU消耗,零拷贝技术通过多种方式实现,下面就来了解一下... 目录一、C++中零拷贝技术的核心概念二、std::string_view 简介三、std::stri

C++高效内存池实现减少动态分配开销的解决方案

《C++高效内存池实现减少动态分配开销的解决方案》C++动态内存分配存在系统调用开销、碎片化和锁竞争等性能问题,内存池通过预分配、分块管理和缓存复用解决这些问题,下面就来了解一下... 目录一、C++内存分配的性能挑战二、内存池技术的核心原理三、主流内存池实现:TCMalloc与Jemalloc1. TCM