当前位置:网站首页>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
边栏推荐
- In depth understanding of USB communication protocol
- AI 击败了人类,设计了更好的经济机制
- 元宇宙带来的创意性改变
- Show progress bar above window
- Tips for this week 131: special member functions and ` = Default`
- Dragging the custom style of Baidu map to the right makes the global map longitude 0 unable to be displayed normally
- Functions and usage of viewswitch
- 数学分析_笔记_第11章:Fourier级数
- Chapter 3 business function development (safe exit)
- 手机版像素小鸟游js戏代码
猜你喜欢
Ansible 学习总结(9)—— Ansible 循环、条件判断、触发器、处理失败等任务控制使用总结
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
Supplementary instructions to relevant rules of online competition
Self made dataset in pytoch for dataset rewriting
深入浅出【机器学习之线性回归】
Test for 3 months, successful entry "byte", my interview experience summary
DatePickerDialog and trimepickerdialog
Deep learning machine learning various data sets summary address
测试3个月,成功入职 “字节”,我的面试心得总结
Function and usage of numberpick
随机推荐
青年时代历练和职业发展
Easy to understand [linear regression of machine learning]
Actionbar navigation bar learning
[trusted computing] Lesson 13: TPM extended authorization and key management
【4500字归纳总结】一名软件测试工程师需要掌握的技能大全
科学家首次观察到“电子漩涡” 有助于设计出更高效的电子产品
Functions and usage of imageswitch
Deep learning machine learning various data sets summary address
带动画的列表选中js特效
讨论| 坦白局,工业 AR 应用为什么难落地?
开发一个小程序商城需要多少钱?
[OKR target management] case analysis
Dragging the custom style of Baidu map to the right makes the global map longitude 0 unable to be displayed normally
DatePickerDialog and trimepickerdialog
企业经营12法的领悟
Functions and usage of ratingbar
Threshold segmentation based on RGB image and threshold adjustment by sliding
Chapter 2 building CRM project development environment (building development environment)
Cf:c. factors and powers of two [DP + sort + Select Board + select several numbers equal to the minimum number of known sums]
漫画 | 宇宙第一 IDE 到底是谁?