在更新特定列和特定值时触发插入 mysql

Trigger to insert on update of specific column and specific value mysql

我有 table 个用户

id | status | created_at | updated_at
----------------------------------------
1  | 0      | 2020-07-23 17:02:49 | 2020-07-23 17:02:49

2  | 0      | 2020-07-23 17:09:24 | 2020-07-23 17:09:24

想要在状态更新为 1 时在新的 table 中插入一条记录,并且更新的行 ID 的计数在 status_count_logs

id | user_id | status_count | created_at
-----------------------------------------

status_count 将是该特定用户的先前值 + 1。 我为 status_count 不递增创建了一个触发器,我怎样才能让用户 ID 插入触发器。

示例:

UPDATE `users` SET `status`='1' WHERE `id`='2';

执行上述查询时,新行应插入 status_count_logs 中,值为

user_id = 2, status_count = previous status_count for user_id + 1

status_count 不递增。

下面是我的触发器

DELIMITER $$
DROP TRIGGER IF EXISTS STATUS_UPDATE_LOGS$$
CREATE TRIGGER STATUS_UPDATE_LOGS AFTER UPDATE ON `users`
FOR EACH ROW BEGIN
    DECLARE s_count integer;
    SET @s_count := (SELECT CASE WHEN MAX(status_count) IS NOT NULL THEN MAX(status_count) + 1 ELSE 0 + 1 END FROM status_count_log WHERE id = NEW.id);
    
  IF NEW.status = 1 THEN
    INSERT INTO status_count_log (user_id, status_count, created_at) VALUES (NEW.id, @s_count, NOW());
  END IF;
END$$
DELIMITER ;

WHERE id = NEW.id 应该是 WHERE user_id = NEW.id

DROP TABLE IF EXISTS STATUS_COUNT_LOG;
CREATE TABLE STATUS_COUNT_LOG
(USER_ID INT,STATUS_COUNT INT,CREATED_AT DATETIME);

DELIMITER $$
DROP TRIGGER IF EXISTS T$$
CREATE TRIGGER T AFTER UPDATE ON `users`
FOR EACH ROW BEGIN
    #DECLARE status_count integer;
    SET @status_count := (SELECT CASE WHEN MAX(status_count) IS NOT NULL THEN MAX(status_count) + 1 
                                            ELSE 0 + 1 END 
                                  FROM status_count_log
                                  where user_id = new.id );
    
  IF NEW.status = 1 THEN
    INSERT INTO status_count_log (user_id,status_count, created_at) VALUES (new.id,@status_count, NOW());
  END IF;
END$$
DELIMITER ;
truncate table status_count_log;
UPDATE USERS SET STATUS = 1 WHERE ID = 1;
UPDATE USERS SET STATUS = 1 WHERE ID = 1;

SELECT * FROM STATUS_COUNT_LOG;

+---------+--------------+---------------------+
| USER_ID | STATUS_COUNT | CREATED_AT          |
+---------+--------------+---------------------+
|       1 |            1 | 2020-07-24 13:45:38 |
|       1 |            2 | 2020-07-24 13:45:38 |
+---------+--------------+---------------------+
2 rows in set (0.001 sec)