MySQL advanced three tricks (three) to see the real "trigger (Trigger)" in the face

Origins trigger (Trigger) of

  • MySQL is the most popular open source RDBMS, is widely used in the community and businesses. Trigger is one of the three new functions MySQL increase (exalted version) in the 5.0.1, two other fellow is a view (view) and a stored procedure (procedure). They belong to a relatively "advanced" point database necessary functions.

table of Contents

 

First, what is the trigger

MySQL trigger action

Second, the trigger grammar

1. Create four elements of grammar

2. syntax formula

3. Syntax Parameter Description

4. NEW and OLD Detailed keyword

Third, the practical application

1. Data Preparation

2. Use Cases

# Insert Trigger - Cascade insert

# Delete triggers - cascading deletes

# Update Trigger - real-time updates

Fourth, what triggers defective human arena @

V. Summary


First, what is the trigger


       Trigger (trigger): monitoring certain conditions, and trigger the execution of certain operations. A trigger is triggered automatically executed when changes occur in the data table, which is associated with a special event table stored procedure, its execution is not called by the program, not manually start, but is triggered by an event, such as when to it is activated when a list operation performed (insert, delete, update). That triggers only execute DML event (insert, update and delete)


MySQL trigger action

1. safety. May enable a user database based on the value of the database operation has certain rights.

  • Time limits may be based on a user's operation, for example, after hours and on holidays is not allowed to modify the database data.
  • Based on data in the database can restrict the user's actions, such as increases in the price of the stock does not allow more than 10% of the time.

2. audit. You can track user actions on the database .   

  • Audit statement user to operate the database.
  • The user updates to the database written to the audit table.

3. implement complex data integrity rules

  • To achieve non-standard data and checks integrity constraints. Triggers can produce more complex than the rule restrictions. With different rules, triggers can reference columns or database objects. For example, a trigger can roll back any attempt to eat into the margin over their own futures.
  • Providing a variable default values.

4. The implementation of complex non-standard database-related integrity rules. Triggers can be related tables in the database comic update .

For example, delete trigger auths on the table columns can result in corresponding author_code delete rows in the other table matching.

  • Cascade modify or delete rows matching other table when modifying or deleting.
  • When modify or delete the matching rows in other tables set to NULL values.
  • When modify or delete the row subtend table matching set to default values.
  • Triggers can refuse to roll back those changes or damage related to the integrity of the data update attempted to cancel the transaction. When a key is inserted into its external primary key does not match, the trigger will work. For example, an insert may be generated on the trigger books.author_code column, if a certain value and the new value does not match the column auths.author_code inserted is rolled back.

The data table in real time in synchronization replication.

6. The automatic calculation of data values, if the value of the data reaches certain requirements, specific treatment is performed. For example, if the company's funds on account of less than 50,000 yuan immediately send warning data to the financial officers.


Second, the trigger grammar

1. Create four elements of grammar

 

  1. Monitoring points (table)
  2. Monitor events (insert | update | delete)
  3. Trigger time (after | before)
  4. Trigger event (insert | update | delete)

2. syntax formula

CREATE TRIGGER <trigger_name>  
  
  BEFORE|AFTER

  INSERT|UPDATE|DELETE  ON <table_name> # 表名
  
  FOR EACH ROW  # 这句话在mysql是固定的

  BEGIN

  <触发的SQL语句>(调用NEW/OLD参数);

  END

3. Syntax Parameter Description

  1. TRIGGER the CREATE <trigger_name>  --- trigger must have a name, up to 64 characters, may later be accompanied by a delimiter. It is named in MySQL and other basic objects alike.
  2. The BEFORE {|} an AFTER  --- triggering time is set triggers: event can be set to the front or rear ( front: Usually for verification; after: for general association ).
  3. INSERT {| UPDATE | DELETE}  - set trigger events: such as the implementation of insert, when the trigger is activated or delete the update process.
  4. ON <table_name>  --- A trigger is a part of a table: When performing on this table INSERT | UPDATE | DELETE operations when it leads to activation of the trigger at the same time, we can not give the same table "One event "arrange two triggers (meaning can not have two Insert flip-flops).
  5. EACH ROW the FOR  --- trigger execution interval (there must be a formula for content): FOR EACH ROW clause tells the trigger action is performed once every other row instead of performing once for the entire table.
  6. <Triggered SQL statement>  --- trigger contains an SQL statement to be triggered: statement here can be any valid statements, including compound statements, but here the same statement by the limitations and functions. Of course, SQL trigger can be called "triggers (INSERT | UPDATE | DELETE) trigger the line that data."

For example, the code below:

create trigger add_stu
after insert on student for each row 
begin
      insert into student_score ( stu_id, score, rank)
        values( NEW.stuid, NEW.username);  -- NEW用来表示将要(BEFORE)或已经(AFTER)插入的新数据
end;

4. NEW and OLD Detailed keyword

MySQL OLD and NEW are defined, where the table is used to indicate the trigger, the trigger of the line data flipflop, a reference to the content of the recording trigger changes, in particular:

  ① In INSERT-type flip-flop, NEW is used to refer to (the BEFORE) or has (an AFTER) insertion of new data;

  ② In the UPDATE-type flip-flop, OLD used to represent the original data to or have been modified, NEW to be or have been modified to represent the new data of;

  ③ In the trigger type DELETE, OLD used to represent the original data to or have been removed;


In addition, in principle, please write simple and efficient trigger the execution of the statement, so as not to waste too much silently resources you do not know!

 

Third, the practical application


1. Data Preparation

I want three days when the annual countdown, performance and stability, so I took was a few old friends to commemorate the ranking data wave (manual scratching their heads). Give us a test data;
( "View" Bowen data in the previous two follow, "stored procedures")

a. student table

CREATE TABLE `student` (
  `ID`  int NOT NULL AUTO_INCREMENT  ,
  `NAME`  varchar(30) NOT NULL ,
  `SEX`  char(2) NOT NULL ,
  `AGE`  int NOT NULL ,
  `CLASS`  varchar(10) NOT NULL ,
  `GRADE`  varchar(20) NOT NULL ,
  `HOBBY`  varchar(100) NULL ,
 PRIMARY KEY (`ID`)
)

# Insert data:

INSERT INTO `student` (`ID`, `NAME`, `SEX`, `AGE`, `CLASS`, `GRADE`, `HOBBY`) VALUES ('1', '陈哈哈', '男', '15', '18班', '9年级', '上网');
INSERT INTO `student` (`ID`, `NAME`, `SEX`, `AGE`, `CLASS`, `GRADE`, `HOBBY`) VALUES ('2', '扈亚鹏', '男', '15', '18班', '9年级', '美食');
INSERT INTO `student` (`ID`, `NAME`, `SEX`, `AGE`, `CLASS`, `GRADE`, `HOBBY`) VALUES ('3', '刘晓莉', '女', '14', '18班', '9年级', '金希澈');
INSERT INTO `student` (`ID`, `NAME`, `SEX`, `AGE`, `CLASS`, `GRADE`, `HOBBY`) VALUES ('4', '朱志鹏', '男', '15', '18班', '9年级', '睡觉');
INSERT INTO `student` (`ID`, `NAME`, `SEX`, `AGE`, `CLASS`, `GRADE`, `HOBBY`) VALUES ('5', '徐立楠', '女', '14', '18班', '9年级', '阅读');
INSERT INTO `student` (`ID`, `NAME`, `SEX`, `AGE`, `CLASS`, `GRADE`, `HOBBY`) VALUES ('6', '顾昊', '男', '15', '5班', '9年级', '篮球');
INSERT INTO `student` (`ID`, `NAME`, `SEX`, `AGE`, `CLASS`, `GRADE`, `HOBBY`) VALUES ('7', '陈子凝', '女', '15', '18班', '9年级', '看电影');

# Insert results:

b. the results table

CREATE TABLE `student_score` (
  `SID` int(11) NOT NULL,
  `S_NAME` varchar(30) NOT NULL,
  `TOTAL_SCORE` int(11) NOT NULL,
  `RANK` int(11) NOT NULL,
 PRIMARY KEY (`SID`)
) 

# Insert data:

INSERT INTO `student_score` (`SID`, `S_NAME`, `TOTAL_SCORE`, `RANK`) VALUES ('1', '陈哈哈', '405', '1760');
INSERT INTO `student_score` (`SID`, `S_NAME`, `TOTAL_SCORE`, `RANK`) VALUES ('2', '扈亚鹏', '497', '1000');
INSERT INTO `student_score` (`SID`, `S_NAME`, `TOTAL_SCORE`, `RANK`) VALUES ('3', '刘晓莉', '488', '1170');
INSERT INTO `student_score` (`SID`, `S_NAME`, `TOTAL_SCORE`, `RANK`) VALUES ('4', '朱志鹏', '405', '1770');
INSERT INTO `student_score` (`SID`, `S_NAME`, `TOTAL_SCORE`, `RANK`) VALUES ('5', '徐立楠', '530', '701');
INSERT INTO `student_score` (`SID`, `S_NAME`, `TOTAL_SCORE`, `RANK`) VALUES ('6', '顾昊', '485', '1286');
INSERT INTO `student_score` (`SID`, `S_NAME`, `TOTAL_SCORE`, `RANK`) VALUES ('7', '陈子凝', '704', '9');

# Insert results:


c. Internet skipping table

CREATE TABLE `student_go_wangba` (
  `SID` int(9) NOT NULL,
  `SGW_NAME` varchar(30) DEFAULT NULL,
  `TIMES` int(9) DEFAULT NULL,
  PRIMARY KEY (`SID`)
) 

# Insert data:

INSERT INTO `student_go_wangba` (`SID`, `SGW_NAME`, `TIMES`) VALUES ('1', '陈哈哈', 15);
INSERT INTO `student_go_wangba` (`SID`, `SGW_NAME`, `TIMES`) VALUES ('2', '扈亚鹏', 1);
INSERT INTO `student_go_wangba` (`SID`, `SGW_NAME`, `TIMES`) VALUES ('3', '刘晓莉', 0);
INSERT INTO `student_go_wangba` (`SID`, `SGW_NAME`, `TIMES`) VALUES ('4', '朱志鹏', 63);
INSERT INTO `student_go_wangba` (`SID`, `SGW_NAME`, `TIMES`) VALUES ('5', '徐立楠', 0);
INSERT INTO `student_go_wangba` (`SID`, `SGW_NAME`, `TIMES`) VALUES ('6', '顾昊', 7);
INSERT INTO `student_go_wangba` (`SID`, `SGW_NAME`, `TIMES`) VALUES ('7', '陈子凝', 0);

# Insert results:

2. Use Cases

# Insert Trigger - Cascade insert

       Data Table: The above three tables, for example; Table students (student), student achievement table (student_score), skipping the number of Internet table (student_go_wangba), have student number (stuid) primary key.   

demand:

  • Need to design a flip flop A, when new students, students need to insert the corresponding information in the results table (student_score) in regard to "score ranking" field to 0.; later scoring updates from the teacher.
  • Need to design a trigger B, when adding new student performance information needs to be inserted in a corresponding student information table skipping Internet (student_go_wangba) in regard to "skipping access number" field to 0; behind the dean "crew cut "to update. (Meaning that the trigger: after insert chain reaction test support)

 So, how to design A trigger it?

  1. First, it is inserted into the Insert a trigger, the table is based on the student;
  2. Then after, events after insertion;
  3. Event content is inserted in the results table, you need to insert school student number and name, number is incremented, and the "score ranking" There is no need.
  • Note: new new represents the value of the newly inserted student

 

Trigger A:

-- 新增触发器A,当student表插入数据时,student_score表生成初始关联数据
DROP TRIGGER IF EXISTS add_stu;
create trigger add_stu
after insert on student for each row 
begin
      INSERT INTO student_score (SID, S_NAME, TOTAL_SCORE, RANK) 
        VALUES (new.ID,new.NAME, 0, 0 );
end;

 

Trigger B:

-- 新增触发器B,当student_score表插入数据时,student_go_wangba表生成初始关联数据
DROP TRIGGER IF EXISTS add_score;
create trigger add_score
after insert on student_score for each row 
begin
      INSERT INTO student_go_wangba (SID, SGW_NAME, TIMES) 
        VALUES (new.SID,new.S_NAME, 0 );
end;

Inquiries about my triggers:

show triggers \G

-- "\G"是干什么用的? 
-- 作用:在shell中树形展示

If you do not have \ G in Navicat, direct "show triggers;" can be. 

show triggers;


Execution of a trigger, the data added to a student table:

INSERT INTO `student` (`ID`, `NAME`, `SEX`, `AGE`, `CLASS`, `GRADE`, `HOBBY`) 
VALUES ('8', '李昂', '男', '15', '18班', '9年级', '看片儿');

The results shown below:
 
while inserting data of three, two flip-flops performed correctly ~
NOTE: table and create triggers, it is proposed to increase is determined: the DROP TRIGGER the IF EXISTS `add_stu`;

# Delete triggers - cascading deletes


Data Table: The above three tables, for example; Table students (student), student achievement table (student_score), skipping the number of Internet table (student_go_wangba), have student number (stuid) primary key.  


Requirements: Some Internet always skipping student was expelled, it is necessary to delete all the information, so as not to discredit the school ~~~  

  • Need to design a trigger C, when deleting new students, students need to delete the corresponding information in the results table (student_score) in.
  • Need to design a flip-flop D, when deleting a new student achievement information, students need to delete the corresponding information in the Internet skipping table (student_go_wangba) in. (Meaning that the trigger: whether to support a chain reaction test after delete)

So, how to design the trigger C it?

  1. First, it is a delete trigger insert, is based on the student's table;
  2. Then after, events after insertion;
  3. Events related content is deleted performance data tables, need to remove the student's school number can be.
  • Note: Old value of student representation in the new deleted .

Trigger C:

-- 新增触发器C,当student表删除数据时,student_score表删除关联数据
DROP TRIGGER IF EXISTS del_stu;
create trigger del_stu
after delete on student for each row 
begin
      DELETE FROM student_score where SID = old.ID;
end;

Trigger D:

-- 新增触发器D,当student_score表删除数据时,student_go_wangba表删除关联数据
DROP TRIGGER IF EXISTS del_score;
create trigger del_score
after delete on student_score for each row 
begin
      DELETE FROM student_go_wangba  where SID = old.SID;
end;

Inquiries about my flip-flops ( Show the Triggers \ G ):

 

Execution of a trigger, delete data from a student table:

DELETE FROM `student` where NAME = '朱志鹏'

The results shown below:

Three delete data, triggers performed correctly. Zhu Zhipeng classmate data wood had been ~
Note: Creating triggers and tables, the proposed increase in judgment: DROP TRIGGER IF EXISTS `del_stu` ;

# Update Trigger - real-time updates

With the Insert trigger, Delete triggers empathy , not repeat them here

 

Fourth, what triggers defective human arena @

Know almost by reference to the following, CSDN Forum, a distant community, to explain a few simple content for your reference:

The question: What are the triggers restrictions and precautions

Answer:        
        Trigger will have the following two restrictions:

  1. Triggers can not call to return data stored program client can not be used using the CALL statement dynamic SQL statements, but allows a program stored data to return trigger parameter, which is stored procedure or function by OUT or INOUT type parameter data return trigger is possible, but the process can not be called directly return data.
  2. The trigger can not be used to display the statement begins implicit mode or end of a transaction, such as START TRANS-ACTION, COMMIT, or ROLLBACK.

        Precautions:

        MySQL triggers accordance BEFORE trigger, line operations, the order of execution of AFTER triggers, any further errors will not continue with the rest of the operation, if the operation table of the transaction, if an error occurs, it will It will be rolled back, if for non-transactional table operation, then it can not be rolled back, and the data may be wrong.

 

Second problem: large-scale systems have to be stored procedures and triggers it?

Answer 1:   

     
We need to clarify two issues:

  1. What is a large system?
  2. What are the application areas of your discussion, it can be roughly divided into two kinds: the Internet, the enterprise

Next give you some examples:

  • SAP, peopleSoft, ERP and other enterprise-level applications

        In general, use stored procedures and triggers, reduce development costs, after all, frequently modify their business logic, but also for GM, will often write some business logic into stored procedures, packages like Oracle will be written, more powerful than a stored procedure .
        Another reason is that the server load is controlled, that is, the number of first access to the system is controlled, not so big, and these data and very critical for this equipment is often used is relatively good, multi-purpose storage cabinets support database.
        

  • Another type of Internet industry

        Such as Taobao, know almost, microblogging, pressure on the database is very large, and often the most likely to become a bottleneck, and multi-purpose PC server support, user quantity growth rate is not controllable amount of users while online access is not available control, and certainly we will do this layer of code business logic into other languages, and can make use of some of the LVS and other types of software and hardware load balancing, and Web server layer of smooth increase or decrease, so as to achieve a linear increase or decrease in favor of large-scale Access.
        
        So whether your system is huge this, we must first divide business support object, the most likely place the system prone to bottlenecks in that?
        Of course, does not mean that the Internet industry is absolutely no application stored procedures, this is not right, Ali had to do to migrate Oracle MySQL system is indeed used, because of historical reasons, and there are some new system is also useful, such as regular night Some operating statistics, but there are controls on the amount. A stored procedure is a good thing, to divide the scene, sub-type of business can be a good grasp.

Answer 2:

 

  • Certainly can not say across the board can or can not be used, different types of systems, different sizes, different historical reasons, there will be different solutions.
  • In general, Web applications often the bottleneck in the DB, so the DB will reduce as much as possible to do things, to make time-consuming service Scale Out, in this case, certainly not use stored procedures; and if only the general applications, there is no problem on performance DB, under appropriate scene, the stored procedure can be used.
  • As for the trigger, I know this stuff but never used. I want to risk control, a problem can quickly find the cause, as far as possible not to use triggers.

 

Answer 3:

  1. PLSQL can greatly reduce parse / exec percentage;
  2. Stored procedures can be done automatically static SQL variable bind;
  3. JDBC stored procedure greatly reduces the interaction network transmission speed;
  4. oracle internal storage commit procedure asynchronously written to, to some extent reduce the like redo logs fall time;
  5. Stored Procedures biggest problem is too much pressure to the database development work, in addition to infrastructure upgrade would be more difficult to decouple;
  6. Trigger is not recommended, trigger actions to resolve to resolve the business layer in the service layer, it would be difficult to maintain, and prone to deadlock.

 

Question three: Why we do not recommend using MySQL triggers and stored procedures use?

Answer 1:

  1. Both stored procedures and triggers are very much tied, my general understanding is a hidden trigger is a stored procedure, because it requires no argument, no show called, often have done in your knowledge a lot of action. From this perspective, because it is hidden, potentially increasing the complexity of the system, non-DBA personnel database will be difficult to understand, because it does not perform simply do not feel its presence.
  2. Again, when it comes to complex logic of nested triggers it is unavoidable, if we involve several stored procedures, coupled with the transaction and so on, it is prone to deadlock, and then when debugging will often go from one of the triggers another, constantly retroactive to cascade, it is easy to make large head. In fact, from the performance, and the flip-flop did not improve performance much, just from the code, it may be easy to achieve business at the time of coding, so my point is: abandon the trigger! The basic function of the trigger can be used to implement stored procedures.
  3. In the coding stored procedure call display is easy to read the code, trigger implicitly calls easily overlooked.
  4. Fatal stored procedure is that transplantation, cross-database stored procedures can not be transplanted, such as stored procedures in advance mysql database, consider the performance to be ported to the oracle above, then all the stored procedures need to be rewritten again.

 

Answer 2:
        This thing is not only high in concurrent with project management systems. If it is user-oriented high-concurrency applications, do not use.
        Triggers and stored procedures themselves difficult to develop and maintain, can not be efficient transplant.

  • Triggers can be replaced with a transaction.
  • Stored procedures can be replaced with a back-end script.

Answer 3:
        I think it came from the two aspects:

  1. Stored procedures need to explicitly call, which means the source code is read when you can know the existence of stored procedures, and triggers must be seen in the database side, easily overlooked.
  2. Mysql trigger itself is not very good, such as after delete unable chain reaction of problems.

        I think it is still on the trigger dominant performance , but is not favored by the above reasons.

V. Summary

  • A trigger is triggered on the line, so delete, add or modify operations may all trigger is activated, so do not write too complex triggers, and do not trigger increases flies, this will insert data, modify or delete bring more serious impact, but also bring the consequences of poor portability, so the design when the trigger must be considered.
  • Trigger is a special storage process, it is inserted, deleted, or modified trigger execution of the data in a specific table, which has a finer and more complex data manipulation capability than the standard functions of the database itself.
Published 91 original articles · won praise 747 · Views 230,000 +

Guess you like

Origin blog.csdn.net/qq_39390545/article/details/105417779