Simple application of mysql trigger

  • Requirement description
    Work encounters such a requirement. There are two tables. One is the user's basic information table. There is a field in the user's basic information table whether to marry. One is that there are child table, spouse table, parent table and other information related to the user in the family relationship table, which is distinguished by a field relative. When you delete your spouse, you need to update whether there is a spouse field in the user table. In fact, using code can also be achieved, but the use of triggers is more brief and more efficient processing. Because the online project does not directly display the official watch, it simulates the real watch to establish a relationship.
  • Create table relationship

Spouse table

CREATE TABLE `tb_mate` (
  `id` bigint(20) NOT NULL,
  `pk_userId` bigint(20) DEFAULT NULL,
  `relative` varchar(20) DEFAULT NULL COMMENT '1=配偶关系 0=其他关系',
  `name` varchar(20) DEFAULT NULL COMMENT '姓名',
  `dr` int(1) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

user table

CREATE TABLE `tb_user` (
  `id` bigint(20) NOT NULL,
  `dr` int(1) DEFAULT NULL COMMENT '删除标示',
  `name` varchar(20) DEFAULT NULL,
  `phone` varchar(11) DEFAULT NULL,
  `flag` smallint(6) DEFAULT NULL COMMENT '配偶标示0 没有 1 有',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Trigger logic: when
updating this spouse table, dr = 1 and deleting this spouse triggers whether the spouse field of the user table is updated to 0. When
dr = 0, the spouse field of the user table is triggered to be 1, so the creation of the trigger statement is as follows.

  • Create trigger
DELIMITER $$
CREATE
    
    TRIGGER `upd_info` AFTER UPDATE ON `tb_mate` 
    FOR EACH ROW BEGIN 
IF(new.relative = 1)
THEN
      UPDATE tb_user SET flag = !new.dr 
      WHERE id = new.pk_userId;
 
END IF;
END;

Summary: According to the actual test, regardless of insert update, (after\before) triggers are related to the transaction. When your code has an error associated trigger will also roll back.

Guess you like

Origin blog.csdn.net/qq_29897369/article/details/103847358