当前位置:网站首页>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

9122cdfb0efee8dd5cea2c895d7f6341.gif

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

9ea5ba0ae26a38f411a0d5ae01da14b9.jpeg

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

9beb210b8c6437599fff479c7ff100f1.jpeg

see

show procedure status;

12fdf30e4ad018d591412c525e8c9bf0.jpeg

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 :@

abb7f0794673056920fd325bb9809f28.jpeg

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

5db44d6aa98a599a760633238b349fdd.jpeg

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

a3ef5b69a3f934778b7b385d1d9195d7.jpeg

With input parameters n, seek 1-n The sum of the

c9469e1e69ae115dc79cff6175252169.jpeg

Input parameters are required n, And output parameters total , seek 1-n The sum of the

1a33ad41951aeb907465fe8cc44bc407.jpeg

requirement age Both input and output variables , Introduce an age , Increase 20

8a2c7c365b3e44d56cb846d450d59a01.jpeg

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 "

302d121f217667cd562fadd809a3a080.jpeg

b524865cd61fd6bec8826399f94ee2e5.jpeg

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

714c96a7e3fb78b483fcee9505c41368.jpeg

da9d69334fdca2389324b1347fe37ec7.jpeg

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 .

9118ab938af2359741f97b17590c1a53.jpeg

a558bf9df5f4afdb78a6bda94498feaa.jpeg

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 .

19f63e0391df36877883f78ce3a3239a.jpeg

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);

815a418997743b898594949fa912b764.jpeg Check the product list

30a694a71da89ad3e7f29a3c1864a70e.jpeg

Create triggers and view

20bf4bc8c30247b57089ec556534ce16.jpeg

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 :

7d38eb15fb641cf4369c4313e484a4fb.jpeg

3cb969ba42116aa11f3d33b5cbfe0ffd.jpeg Reference line variables

requirement : When deleting an order , The goods should be returned , Inventory should be restored ( Delete )

c28d9d083d1cf34ca8c2069a33d615b4.jpeg

requirement : Quantity in the order table 3 Request to change to 2, And let the inventory of the commodity table also change ( Change )

c6901686e6d79e78274f17dbdbaf264a.jpeg

6dd4407d38645d5d2ad8c725a39d4b39.jpeg

0c4bb3fef8acbcafc380d6a982cfde17.jpeg

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 )

aa769af90b7377955104cdf2232f2aa4.jpeg

ebf8cd58722a8aaea07ea332655974c5.jpeg

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 .

af99032490ef4e59e394ecd38aa08879.gif

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 
原网站

版权声明
本文为[AI technology base camp]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071554068244.html