Home > Database > Mysql Tutorial > body text

MySQL Advanced 8 - Use of Triggers

黄舟
Release: 2016-12-29 16:42:47
Original
1161 people have browsed it

A trigger is a special stored procedure that triggers execution when inserting, deleting, or modifying data in a specific table. It has more sophisticated and complex data control capabilities than the standard functions of the database itself.

It has the following characteristics:

Monitoring location: usually the table name

Monitoring event: update/delete/insert

Trigger time: after/ before

Trigger event: update/delete/insert

It cannot be called directly and is actively executed by the database.

example1:

Create table tab1

DROP TABLE IF EXISTS tab1;
CREATE TABLE tab1(
    tab1_id varchar(11)
);
Copy after login

Create table tab2

DROP TABLE IF EXISTS tab2;
CREATE TABLE tab2(
    tab2_id varchar(11)
);
Copy after login

Create trigger: t_afterinsert_on_tab1

Function: Add tab1 table After recording, automatically add the record to the tab2 table

DROP TRIGGER IF EXISTS t_afterinsert_on_tab1;
CREATE TRIGGER t_afterinsert_on_tab1 
AFTER INSERT ON tab1
FOR EACH ROW
BEGIN
     insert into tab2(tab2_id) values(new.tab1_id);
END;
Copy after login

Test it

INSERT INTO tab1(tab1_id) values('0001');
Copy after login


See the result
SELECT * FROM tab1;
SELECT * FROM tab2;
Copy after login
Copy after login

example2:

Create trigger: t_afterdelete_on_tab1

Function: After deleting the tab1 table record, the corresponding record in the tab2 table will be automatically deleted

DROP TRIGGER IF EXISTS t_afterdelete_on_tab1;
CREATE TRIGGER t_afterdelete_on_tab1
AFTER DELETE ON tab1
FOR EACH ROW
BEGIN
      delete from tab2 where tab2_id=old.tab1_id;
END;
Copy after login

Test it

DELETE FROM tab1 WHERE tab1_id='0001';
Copy after login


Look at the results
SELECT * FROM tab1;
SELECT * FROM tab2;
Copy after login
Copy after login

The above is the content of MySQL Advanced 8 - the use of triggers. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!