如果字段已存在,则触发MySQL增量

时间:2016-02-08 10:21:23

标签: mysql triggers

当我插入一个几乎与另一个相同的新行时,我想增加一个字段(唯一的区别是id_progress)。为了清楚起见,我将使用此示例

+-------------+---------+---------+---------+
| id_progress | task_id | case_id | loop_nb |
+-------------+---------+---------+---------+
|         800 | 2001002 |     199 | null    |
|         801 | 2001003 |     199 | null    |
|         802 | 2002001 |     199 | null    |
|         803 | 2002002 |     199 | null    |
|         804 | 2001002 |     200 | null    |
|         805 | 2001002 |     199 | 1       |
|         806 | 2001002 |     199 | 2       |
+-------------+---------+---------+---------+

如果loop_nbtask_id已存在于另一行,我想增加新行的case_id

在此示例中,行805之后添加了行804。知道805800几乎相同,触发器会在插入数据库之前增加loop_nb。

我尝试了一些东西,我很新闻触发这么抱歉我做错了

BEGIN
 DECLARE loop_nb integer;
 SET @loop_nb := (select loop_nb
     from progress 
     where task_id = NEW.task_id 
     AND case_id = NEW.case_id
     DESC LIMIT 1 );
 IF ISNULL(@loop_nb) THEN
     SET @loop_nb := @loop_nb+1;
 END IF;
 SET NEW.loop_nb = @loop_nb;
 END

但问题是我的loop_nb默认为null。我不认为我有权改变它。

还有其他选择吗? 如果我可以将loop_nb的默认值更改为'0'

,我的代码是否可以

1 个答案:

答案 0 :(得分:0)

也许像以下代码可以帮助,至少,给你一些想法。

mysql> DELIMITER //

mysql> DROP TRIGGER IF EXISTS `trg_bi_progress`//
Query OK, 0 rows affected (0.00 sec)

mysql> DROP TABLE IF EXISTS `progress`//
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE `progress` (
    ->   `id_progress` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    ->   `task_id` VARCHAR(7),
    ->   `case_id` INT UNSIGNED,
    ->   `loop_nb` INT UNSIGNED
    -> )//
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TRIGGER `trg_bi_progress` BEFORE INSERT ON `progress`
    -> FOR EACH ROW
    -> BEGIN
    ->   SET NEW.`loop_nb` := (
    ->       SELECT NULLIF(COUNT(`id_progress`), 0)
    ->       FROM `progress`
    ->       WHERE `task_id` = NEW.`task_id`
    ->       AND `case_id` = NEW.`case_id`
    ->     );
    -> END//
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO `progress` (`task_id`, `case_id`)
    -> VALUES
    -> ('2001002', 199),
    -> ('2001003', 199),
    -> ('2002001', 199),
    -> ('2002002', 199),
    -> ('2001002', 200),
    -> ('2001002', 199),
    -> ('2001002', 199)//
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0

mysql> DELIMITER ;

mysql> SELECT
    ->   `id_progress`,
    ->   `task_id`,
    ->   `case_id`,
    ->   `loop_nb`
    -> FROM
    ->   `progress`;
+-------------+---------+---------+---------+
| id_progress | task_id | case_id | loop_nb |
+-------------+---------+---------+---------+
|           1 | 2001002 |     199 |    NULL |
|           2 | 2001003 |     199 |    NULL |
|           3 | 2002001 |     199 |    NULL |
|           4 | 2002002 |     199 |    NULL |
|           5 | 2001002 |     200 |    NULL |
|           6 | 2001002 |     199 |       1 |
|           7 | 2001002 |     199 |       2 |
+-------------+---------+---------+---------+
7 rows in set (0.00 sec)