删除前触发器问题

时间:2017-07-06 22:12:37

标签: mysql triggers delete-row

我需要使用触发器在表中插入另一个表的已删除行的“日志”。

DROP TRIGGER IF EXISTS bajas_pil;
CREATE TRIGGER bajas_pil BEFORE DELETE ON pilotos
  FOR EACH ROW
  BEGIN
    INSERT INTO pilotos_baja (usuario, fecha, hora, dorsal) VALUES (user(), CURRENT_DATE, CURRENT_TIME, OLD.pil_numero);
  END;

我可以添加触发器,但是,当我删除表'pilotos'中的行时,它不会在表'pilotos_abaja'中添加任何行。有人知道它为什么会发生吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

我无法重现这个问题:

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

mysql> DROP TABLE IF EXISTS `pilotos_baja`, `pilotos`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `pilotos` (
    ->   `pil_numero` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> CREATE TABLE IF NOT EXISTS `pilotos_baja` (
    ->   `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    ->   `usuario` VARCHAR(93) NOT NULL,
    ->   `fecha` DATE NOT NULL,
    ->   `hora` TIME NOT NULL,
    ->   `dorsal` BIGINT UNSIGNED NOT NULL
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TRIGGER `bajas_pil` BEFORE DELETE ON `pilotos`
    -> FOR EACH ROW
    ->   INSERT INTO `pilotos_baja` (
    ->     `usuario`,
    ->     `fecha`,
    ->     `hora`,
    ->     `dorsal`)
    ->   VALUES (
    ->     USER(),
    ->     CURRENT_DATE,
    ->     CURRENT_TIME,
    ->     OLD.`pil_numero`);
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO `pilotos`
    -> VALUES (NULL), (NULL), (NULL);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT `pil_numero`
    -> FROM `pilotos`;
+------------+
| pil_numero |
+------------+
|          1 |
|          2 |
|          3 |
+------------+
3 rows in set (0.00 sec)

mysql> DELETE FROM `pilotos`;
Query OK, 3 rows affected (0.00 sec)

mysql> SELECT
    ->   `usuario`,
    ->   `fecha`,
    ->   `hora`,
    ->   `dorsal`
    -> FROM
    ->   `pilotos_baja`;
+-----------+------------+----------+--------+
| usuario   | fecha      | hora     | dorsal |
+-----------+------------+----------+--------+
| user@host | 2010-01-01 | 00:00:01 |      1 |
| user@host | 2010-01-01 | 00:00:01 |      2 |
| user@host | 2010-01-01 | 00:00:01 |      3 |
+-----------+------------+----------+--------+
3 rows in set (0.00 sec)

请参阅db-fiddle