MySQL triggers application

MySQL trigger is introduced in version 5.0. For the need to make changes to the database cascade it is very suitable for use, such as the need to change the real-time monitoring of a field in a particular table in the need to make the appropriate treatment. Trigger although powerful, reliable and easy implementation of many complex functions, " to use MySQL UDFs to call gearman distributed task distribution system ", " sphinx application (c) -sphinx distributed, XML data sources, Gearman, UpdateAttributes " and follow-up will be introduced to the user NOSQL database tables are used to trigger. However, caution should trigger, trigger abuse will result in the database, and application maintenance difficult. 1. Create a trigger grammar
CREATE
	[DEFINER = { user | CURRENT_USER }]
	TRIGGER trigger_name
	trigger_time trigger_event
	ON tbl_name FOR EACH ROW
	trigger_body

trigger_time: { BEFORE | AFTER }
trigger_event: { INSERT | UPDATE | DELETE }
Syntax relevant parts of the description: 1.1 Authorized and recycling to create a trigger requires CREATE TRIGGER permissions:
grant create trigger on `database_naem`.`table_name` to `user_name`@`ip_address`;
Rights to recover:
revoke create trigger on `database_naem`.`table_name` from `user_name`@`ip_address`;
1.2 trigger_name need to trigger command, up to 64 characters, it is recommended to use the name of the table _ an abbreviation for the type of trigger method name. As ttlsa_posts_bi (Table ttlsa_posts, triggers occur before before insert) 1.3 DEFINER clause when the trigger is activated, check the access permissions to ensure the safe use of triggers. 1.4 trigger_time define the trigger trigger time. It can be set to record changes occur before or after the line. 1.5 trigger_event define the trigger trigger event. Event triggers are: 1.5.1 INSERT: When a new trigger when inserted into the table row. Such as INSERT, LOAD DATA, and REPLACE statements. UPDATE: Fires when a row of data is changed. As an UPDATE statement. DELETE: Fires when a row is deleted from the table. Such as DELETE, and REPLACE statements. Note: DROP TABLE and TRUNCATE TABLE statement does not trigger the trigger, because they do not use DELETE. Also delete a partition table will not be triggered. There is a potential for confusion, such as INSERT INTO ... ON DUPLICATE KEY UPDATE ... depends on whether there are duplicate key row. It has the same trigger event triggers and trigger several times can not be created on a table. As for a table can not create two BEFORE UPDATE trigger, however, create a BEFORE UPDATE and a BEFORE INSERT or a BEFORE UPDATE and an AFTER UPDATE trigger. 1.6 FOR EACH ROW clause defines the trigger execution interval. FOR EACH ROW clause defines the trigger action is executed once every other line instead performed once for the entire table. 1.7 trigger_body to trigger the clause contains the SQL statement executed. It can be any valid statements, including the compound statement (BEGIN ... need to use END structure), flow control statements (if, case, while, loop, for, repeat, leave, iterate), variable declaration (DECLARE) and assignment (SET), exception handling statement, allowing conditional statements, the statements herein subject the same restrictions and functions. 1.7.1 OLD and NEW trigger SQL statements may be associated with any column in the table, identified by the OLD and NEW using the column names, such as OLD.col_name, NEW.col_name. A value before being updated or deleted rows OLD.col_name existing association. NEW.col_name associated insert a new row or update the value of a conventional line. For the INSERT statement, only NEW is legal. Otherwise it will error: ERROR 1363 (HY000): There is no OLD row in on INSERT trigger for DELETE statements, only OLD is legal. Otherwise it will error: ERROR 1363 (HY000): There is no NEW row in on DELETE trigger for an UPDATE statement, NEW and OLD can be used simultaneously. 2. Examples 2.1 to create tables in " mysqludf_json relational data in JSON encoding " a text table created. Subsequent users will migrate to nosql database table.
mysql> create table `ttlsa_users` (
    -> `uid` int(11) unsigned,
    -> `username` varchar(40) NOT NULL,
    -> `password` varchar(40) NOT NULL,
    -> `createtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    -> PRIMARY KEY (`uid`)
    -> );
Create another table to store the data trigger action.
mysql> create table `ttlsa_users3` (
    -> `uid` int(11) unsigned,
    -> `userinfo` varchar(200),
    -> );
2.2 Creating Triggers
mysql> delimiter //
mysql> create trigger ttlsa_users_ai
    -> after insert on ttlsa_users
    -> for each row
    -> insert into ttlsa_users3 (uid, userinfo) values(uid, json_object(NEW.uid, NEW.username, NEW.password));
    -> //

mysql> create trigger ttlsa_users_au
    -> after update on ttlsa_users
    -> for each row
    -> update ttlsa_users3 set userinfo=json_object(NEW.uid, NEW.username, NEW.password) where uid=OLD.uid;
    -> //
2.3 Test
mysql> insert into ttlsa_users values (890,'xuhh',md5('abc'),NULL,'test trigger')//
Query OK, 1 row affected (0.01 sec)

mysql> select * from ttlsa_users//
+-----+-------------+----------------------------------+---------------------+------------------------------------+
| uid | username    | password                         | createtime          | json_data                          |
+-----+-------------+----------------------------------+---------------------+------------------------------------+
| 888 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 11:27:01 | \website\ - "http://www.ttlsa.com" |
| 889 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 14:08:44 | xuhh                               |
| 890 | xuhh        | 900150983cd24fb0d6963f7d28e17f72 | 2013-08-14 16:40:49 | test trigger                       |
+-----+-------------+----------------------------------+---------------------+------------------------------------+
3 rows in set (0.00 sec)

mysql> select * from ttlsa_users3//
+-----------------------------------------------------------------------------+------+
| userinfo                                                                    | uid  |
+-----------------------------------------------------------------------------+------+
| {"uid":890,"username":"xuhh","password":"900150983cd24fb0d6963f7d28e17f72"} |  890 |
+-----------------------------------------------------------------------------+------+
2 rows in set (0.00 sec)

mysql> update ttlsa_users set password='test_update' where uid=890//
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from ttlsa_users//
+-----+-------------+----------------------------------+---------------------+------------------------------------+
| uid | username    | password                         | createtime          | json_data                          |
+-----+-------------+----------------------------------+---------------------+------------------------------------+
| 888 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 11:27:01 | \website\ - "http://www.ttlsa.com" |
| 889 | ttlsa_admin | 6a6e41c9b741f740cfa5f266b249d452 | 2013-08-10 14:08:44 | xuhh                               |
| 890 | xuhh        | test_update                      | 2013-08-14 16:41:33 | test trigger                       |
+-----+-------------+----------------------------------+---------------------+------------------------------------+
3 rows in set (0.00 sec)

mysql> select * from ttlsa_users3//
+-----------------------------------------------------------------------------+------+
| userinfo                                                                    | uid  |
+-----------------------------------------------------------------------------+------+
| {"uid":890,"username":"xuhh","password":"test_update"}                      |  890 |
+-----------------------------------------------------------------------------+------+
2 rows in set (0.00 sec)
3. Management 3.1 lists the trigger
mysql> SHOW TRIGGERS  like '%ttlsa%';  触发器名称匹配%ttlsa%
*************************** 1. row ***************************
             Trigger: ttlsa_users_ai
               Event: INSERT
               Table: ttlsa_users
           Statement: insert into ttlsa_users3 (uid,userinfo) values(NEW.uid,json_object(NEW.uid, NEW.username, NEW.password))
              Timing: AFTER
             Created: NULL
            sql_mode: NO_ENGINE_SUBSTITUTION
             Definer: [email protected]
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
*************************** 2. row ***************************
             Trigger: ttlsa_users_au
               Event: UPDATE
               Table: ttlsa_users
           Statement: update ttlsa_users3 set userinfo=json_object(NEW.uid, NEW.username, NEW.password) where uid=OLD.uid
              Timing: AFTER
             Created: NULL
            sql_mode: NO_ENGINE_SUBSTITUTION
             Definer: [email protected]
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: latin1_swedish_ci
2 rows in set (0.00 sec)
mysql> SHOW TRIGGERS; 列出所有
mysql> SHOW TRIGGERS  from database_name;  列出数据库的触发器
mysql> SHOW CREATE TRIGGER trigger_name;    查看创建触发器
*************************** 1. row ***************************
               Trigger: ttlsa_users_ai
              sql_mode: NO_ENGINE_SUBSTITUTION
SQL Original Statement: CREATE DEFINER=`root`@`127.0.0.1` trigger ttlsa_users_ai after insert on ttlsa_users for each row insert into ttlsa_users3 (uid,userinfo) values(NEW.uid,json_object(NEW.uid, NEW.username, NEW.password))
  character_set_client: utf8
  collation_connection: utf8_general_ci
    Database Collation: latin1_swedish_ci
1 row in set (0.01 sec)
3.2 INFORMATION_SCHEMA.TRIGGERS表
mysql> SELECT * FROM INFORMATION_SCHEMA.TRIGGERS  WHERE TRIGGER_SCHEMA='test' AND TRIGGER_NAME='ttlsa_users_au'\G
*************************** 1. row ***************************
           TRIGGER_CATALOG: def
            TRIGGER_SCHEMA: test
              TRIGGER_NAME: ttlsa_users_au
        EVENT_MANIPULATION: UPDATE
      EVENT_OBJECT_CATALOG: def
       EVENT_OBJECT_SCHEMA: test
        EVENT_OBJECT_TABLE: ttlsa_users
              ACTION_ORDER: 0
          ACTION_CONDITION: NULL
          ACTION_STATEMENT: update ttlsa_users3 set userinfo=json_object(NEW.uid, NEW.username, NEW.password) where uid=OLD.uid
        ACTION_ORIENTATION: ROW
             ACTION_TIMING: AFTER
ACTION_REFERENCE_OLD_TABLE: NULL
ACTION_REFERENCE_NEW_TABLE: NULL
  ACTION_REFERENCE_OLD_ROW: OLD
  ACTION_REFERENCE_NEW_ROW: NEW
                   CREATED: NULL
                  SQL_MODE: NO_ENGINE_SUBSTITUTION
                   DEFINER: [email protected]
      CHARACTER_SET_CLIENT: utf8
      COLLATION_CONNECTION: utf8_general_ci
        DATABASE_COLLATION: latin1_swedish_ci
1 row in set (0.00 sec)
3.3 Delete Trigger
mysql> drop trigger trigger_name;
For reprint please indicate the source: Application MySQL trigger  http://www.ttlsa.com/html/2335.html

Reproduced in: https: //my.oschina.net/766/blog/211217

Guess you like

Origin blog.csdn.net/weixin_33972649/article/details/91546562