当前位置:网站首页>Using stored procedures, timers, triggers to solve data analysis problems
Using stored procedures, timers, triggers to solve data analysis problems
2022-07-07 18:07:00 【AI technology base camp】
author | python And data analysis
source | Jay's IT The journey
Many do development 、 Small partners in database related work may often use MySQL Stored procedure 、 Timer 、 Trigger these advanced functions , But do data analysis or data processing , We also need to master these skills , To solve specific business problems . such as : Make automated reports , If the data needs to be updated in real time every day ( Incremental crawler )、 Calculate a business indicator regularly 、 Want to monitor the data increase in database tables in real time 、 Delete 、 Change the situation, etc .
Outline of the article
One 、 stored procedure
1、 What is a stored procedure , What's the usage? ?
The process : Put a number of SQL Statements are encapsulated , Name it
stored procedure : We store this procedure in the database , It is a little similar to the functions used in programming , The difference is that the function has a return value , The procedure does not return a value , The same point is that the code is encapsulated and reusable , You can pass it on , Call to execute .
benefits :① Code encapsulation is reusable ② You can receive 、 Returns the parameter ③ Reduce network interaction 、 Improve efficiency
2、 How stored procedures are used
establish
create procedure name ()
begin
sql sentence ;
end
see
show procedure status;
call
call name ();
Delete
drop procedure if exists name ;
3、 Variables in stored procedures
Types and definitions of variables
stay SQL There are two kinds of variables in :
① System variables :@@
② Custom variable :@
Stored procedures are programmable , It means that variables can be used 、 expression 、 Control structure , In the stored procedure , Declare variables with declare.
Format :declare Variable name Variable type 【default The default value is 】
Variable operation and control structure
The assignment of a variable , There are two ways :
① set Variable name = value
② set Variable name := value
if | else Control the structure syntax format
if Conditions 1 then
sql sentence ;
else if Conditions 2 then
sql sentence ;
else
sql sentence ;
end if
Parameter passing in stored procedures
To make stored procedures more flexible , Parameters can be passed , There are three types of parameters :
① in: Parameters as input , Pass in
② out: Parameter as output , It can be used as a return value
③ inout: Parameters can be passed in or entered
Format : in|out|inout Parameter name Parameter type
Use loops in stored procedures
while Circular format :
while Conditions do
sql sentence ;
end while
Print 1 - 100 The sum of the
With input parameters n, seek 1-n The sum of the
Input parameters are required n, And output parameters total , seek 1-n The sum of the
requirement age Both input and output variables , Introduce an age , Increase 20
Two 、 Timer
1、 What is a timer , How to use it? ?
The so-called timer , Is to run the specified functions and code regularly ,MySQL The timer of is MySQL Events .
In the development process, we often encounter such a problem : Every day or every month, it is necessary to implement one SQL Statement or update or delete data . I don't know MySQL When timer , Yes, it is Python Program code to operate the data table , then Python Program , Put it on the server to run the scheduled task . Now use the timer , It can be operated at the data level , Very convenient .
Grammatical structure
create event [if not exists] Event name
[definer = user] Optional parameters . Of board ⾏ The event ⽤⼾, If you do not specify, the default is the current ⽤⼾
on schedule Timing setting . Define event execution ⾏ The frequency of , You can specify a specific time or execute periodically
[on completion [not] preserve ] Optional parameters . The default is not, surface ⽰ After the time expires ⽴ Delete immediately ( Note that it is not inactive );on completion preserve surface ⽰ After the time expires, it will continue to be retained
[enable | disable | disable on slave] Optional parameters . Default enable. Event activation 、 Do not activate 、 Do not activate from the service ( Events are created by the master service provider and assigned to the slave server , Execute only on the main service )
[comment " notes "] Optional parameters .
do What happened Define the sql sentence , If the statement has more ⾏ need ⽤ begin end Cover up
Specify a time to execute
at Clause : The requirement here is timestamp Time format ,⼀ The general format is “ Point in time + interval Time unit ”. Indicates at what time node , for example :current_timestamp + interval 2 minute
requirement : Two minutes later event_test Table insertion ⼊⼀ statement " Event started "
Be careful : Because the default parameter is on completion not preserve, The event will be automatically deleted after running
The cycle time is executed regularly :
every Clause : The format is “ Numbers + Time unit ”, Represents the time period , for example :1 hour / 2 minute / 3 second
starts Clause : Optional , keep pace with timestamp value , Indicates the time point when the event started , If not specified, it is the current time
ends Clause : Optional , keep pace with timesatamp value , Indicates the time to stop execution , without ends It means infinite execution
requirement : New data table event_test, Insert it every minute ⼊⼀ Data , To 5 Minutes end
matters needing attention
1、 Events need to be activated , The event will be executed ,show events Before you can view it .⼀ The first is global parameter on ,⼀ The first is the opening of the event
SET GLOBAL event_scheduler = 1;
Set the event status to enable:
ALTER EVENT event_name ON COMPLETION PRESERVE ENABLE; Turn on
ALTER EVENT event_name ON COMPLETION PRESERVE DISABLE; close
2、 It's off navicat, The event will not close , Shut down the MySQL The server will be shut down
3、 When executing multiple statements , You may need to modify the end delimiter , such as :delimiter $
4、 If the start time of the event has passed , Although the creation statement will not report an error , But events are not created and executed
5、 event ⾥⾯ Events cannot be nested , But events can be used in stored procedures
6、 Use... In events select、show Waiting for the return result statement is meaningless , But you can use select into、insert into Wait for the statement that stores the result
7、 Be careful not to repeat the event scheduling in a short period , Otherwise, there will be problems with the data . For example, execute every minute 100w Row data , There will be a problem with this , If you really need it, you can use row lock at this time 、 Watch lock
8、 event ⽆ Method to pass parameters , But you can use stored procedures with parameters in events
Timers can be combined with stored procedures
Now use the timer , You can operate at the data level , Do it regularly sql Statement or group sql sentence ( stored procedure ), Set up scheduled tasks , It can be done by navicat —— Other —— event , View the definition of the current event , plan , Of course, you can also manually complete the above operations .
3、 ... and 、 trigger
1、 What is a trigger , The application scenario is ?
Triggers are a special kind of transaction , You can monitor data operations ( Change log of data table ), Include insert | update | delete, And trigger related operations insert | update | delete, Use triggers , It can not only simplify the procedure , It can also increase the flexibility of the program .
Application scenarios ①: When adding or deleting data to a table , Synchronization operations need to be performed in related tables , such as : When an order is generated , The inventory of the products purchased by the order is reduced accordingly .
Application scenarios ②: When the value of a column of data in the table is related to the data in other tables , such as : A customer is in arrears , When generating an order , A trigger is designed to determine whether the accumulated debt of the user exceeds the maximum .
Application scenarios ③: When tracking a table , For example, when a new order is generated , It is necessary to inform relevant personnel to handle , At this time, you can add triggers in the order table to realize .
2、 How to use triggers
establish
Triggers only support row level triggering ( Each line is affected , All triggers execute , It is called row level trigger ), Statement level triggering is not supported .
Create trigger Trigger Name
before/after
insert/update/delete
on Table name for each row # Line level triggers
Begin
trigger_state;
end
see
Show triggers;
Delete
Drop trigger database . Trigger Name ;
requirement : List of existing products goods, The order sheet orders, Next order , Commodities should be reduced accordingly ( Buy some goods , Just a few stocks ), The analysis is as follows :
Who to watch :orders
Watch the action :insert
Trigger time :after
Triggering event :update
CREATE TABLE goods(gid INT,name VARCHAR(10),num SMALLINT);
CREATE TABLE ord(oid INT ,gid INT, buy_num SMALLINT)
INSERT INTO goods VALUES (1,'cat',20),(2,'dog',90),(3,'pig',26);
Check the product list
Create triggers and view
I found that writing triggers like this is not flexible
3、 Trigger references row variables
Use the alias old、new To refer to the changed record content in the trigger . Be careful :
Reference line variables
requirement : When deleting an order , The goods should be returned , Inventory should be restored ( Delete )
requirement : Quantity in the order table 3 Request to change to 2, And let the inventory of the commodity table also change ( Change )
requirement : If it's left now 26 only pig, But customers place orders to buy 27 only , Can we prevent , Could you please buy_num > num when , take buy_num Automatically change to num( In depth understanding of before and after The difference between )
The above introduces to you , How to analyze data in work , application MySQL Stored procedure 、 Timer 、 Trigger to automatically update data . Of course , use Python Or other programming languages , Personally, I think that at the data level , It's simpler 、 Efficient 、 Stable . It also depends on your current business scenario . I hope this article can provide you with a way to solve the problem .
Looking back
It's too voluminous !AI High accuracy of math exam 81%
Data analysis you choose Pandas Or choose SQL?
2D Transformation 3D, Look at NVIDIA's AI“ new ” magic !
How to use Python Realize the security system of the scenic spot ?
Share
Point collection
A little bit of praise
Click to see
边栏推荐
- [principle and technology of network attack and Defense] Chapter 7: password attack technology Chapter 8: network monitoring technology
- Function and usage of numberpick
- 备份阿里云实例-oss-browser
- Toast will display a simple prompt message on the program interface
- 2022年理财有哪些产品?哪些适合新手?
- 2021-06-28
- USB通信协议深入理解
- List selection JS effect with animation
- Taffydb open source JS database
- 数字化转型的主要工作
猜你喜欢
Function and usage of numberpick
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
三仙归洞js小游戏源码
Toast will display a simple prompt message on the program interface
[tpm2.0 principle and Application guide] Chapter 1-3
Yarn capacity scheduler (ultra detailed interpretation)
What is agile testing
Understanding of 12 methods of enterprise management
Self made dataset in pytoch for dataset rewriting
讨论| 坦白局,工业 AR 应用为什么难落地?
随机推荐
MySQL index hit level analysis
Tips for this week 131: special member functions and ` = Default`
【蓝桥杯集训100题】scratch从小到大排序 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第17题
Hutool - 轻量级 DB 操作解决方案
Click on the top of today's headline app to navigate in the middle
golang 客户端服务端登录
万字保姆级长文——Linkedin元数据管理平台Datahub离线安装指南
元宇宙带来的创意性改变
基于百度飞浆平台(EasyDL)设计的人脸识别考勤系统
Ansible learning summary (9) -- ansible loop, condition judgment, trigger, processing failure and other task control use summary
[principles and technologies of network attack and Defense] Chapter 3: network reconnaissance technology
深入浅出图解CNN-卷积神经网络
手机app外卖订餐个人中心页面
AI 击败了人类,设计了更好的经济机制
Actionbar navigation bar learning
Win11C盘满了怎么清理?Win11清理C盘的方法
深度学习-制作自己的数据集
Chapter 3 business function development (safe exit)
Toast will display a simple prompt message on the program interface
目标管理【管理学之十四】