如何确定哪些列更新?

时间:2016-05-14 17:42:38

标签: mysql sql sql-update sql-insert

我有这些表格:

// users
+----+--------+--------------+------------+---------------------------+
| id |  name  |    phone     | postalcode |           email           |
+----+--------+--------------+------------+---------------------------+
| 1  | john   | 0338294214   | 65462345   | fer.74@gmail.com          |
| 2  | jack   | 0657359930   | 93827424   | jack_m@yahoo.com          |
| 3  | peter  | 0083247242   | 99849422   | mv2003@hotmail.com        |
+----+--------+--------------+------------+---------------------------+

// notifications
+----+---------+---------------+------------+
| id | user_id |    content    | timestamp  |
+----+---------+---------------+------------+
| 1  | 2       | phone updated | 1452642595 |
+----+---------+---------------+------------+

此外,我在users table ::

上有此触发器 AFTER UPDATE
DELIMITER //
CREATE TRIGGER `send_notification` AFTER UPDATE ON `users`
FOR EACH ROW BEGIN
  INSERT INTO notification(user_id, content, timestamp)
                    values(new.id, "phone updated", UNIX_TIMESTAMP())
END
//
DELIMITER 

我正在尝试做的就是在phone列更新时执行该触发器。 (不是在namepostalcodeemail更新时)。我该如何定义这个条件?

1 个答案:

答案 0 :(得分:2)

在触发器中,我们可以使用oldnew来引用列的值,更新前的值以及要分配的新值。

示例:

  IF NOT ( new.phone <=> old.phone ) THEN
    -- value assigned to phone column changed
  ELSE
    -- value of phone column unchanged
  END IF;  

<=>(宇宙飞船运营商)是一个NULL安全比较,即使比较NULL值,它也会返回TRUE或FALSE。