MySQL 触发插入/更新事件

标签 mysql triggers insert insert-update

所以我有两张这样的表...

ext_words
-------------
| id | word |
-------------
| 1  | this |
-------------
| 2  | that |
-------------
| 3  | this |
-------------

ext_words_count
---------------------
| id | word | count |
---------------------
| 1  | this |   2   |
---------------------
| 2  | that |   1   |
---------------------

我正在尝试创建一个触发器,它将:

  • ext_words.word 更新时更新 ext_words_count.count

为了让事情更复杂,

  • 如果 ext_words 更新时 ext_words_count 中不存在 ext_words.word,我想将其插入 ext_words_count 并将 count 设置为 1。

我一直在研究类似的问题:
1. Before / after insert trigger using auto increment field , 和
2. Using Trigger to update table in another database
试图将 2 结合起来。这是我到目前为止所拥有的:

DELIMITER $$
CREATE TRIGGER update_count
AFTER UPDATE ON ext_words
FOR EACH ROW
BEGIN

  UPDATE ext_words_count
    SET word_count = word_count + 1
  WHERE word = NEW.word;

END;
$$
DELIMITER ;

非常感谢任何建议和指导。或者可能是我忽略的另一种方法,并且一如既往地提前感谢!

更新:
我选择使用 2 个触发器,一个用于 INSERT,一个用于 UPDATE,因为我对 MySQL 中的条件语句不太熟悉。

DELIMITER $$
CREATE TRIGGER insert_word AFTER INSERT ON ext_words
  FOR EACH ROW
    BEGIN
      INSERT IGNORE INTO ext_words_count (word) VALUES (NEW.word);
    END;
$$
DELIMITER ;

DELIMITER $$
CREATE TRIGGER update_word AFTER UPDATE ON ext_words
  FOR EACH ROW
    BEGIN
      UPDATE ext_words_count 
      SET word_count = word_count + 1 
      WHERE word = NEW.word;
    END;
$$
DELIMITER ;

INSERT 查询运行良好,但是 UPDATE 查询没有更新 word_count。我在更新查询中遗漏了什么......?

最佳答案

在 Grijesh 的完美帮助和他对使用条件语句的建议下,我能够获得同时完成这两项任务的 ONE 触发器。再次感谢 Grijesh

 DELIMITER $$ 
 CREATE TRIGGER update_count AFTER INSERT ON ext_words 
 FOR EACH ROW 
   BEGIN
     IF NOT EXISTS (SELECT 1 FROM ext_words_count WHERE word = NEW.word) THEN
       INSERT INTO ext_words_count (word) VALUES (NEW.word);
   ELSE
       UPDATE ext_words_count SET word_count = word_count + 1 WHERE word = NEW.word;
   END IF;
  END $$    
 DELIMITER;   

关于MySQL 触发插入/更新事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15975877/

相关文章:

php - php 和 SQL 查询的数组问题

mysql - 与 PostgreSQL 相比,为什么 Mysql 不需要真空?

javascript - 更改 URL 哈希更改时的脚本代码

mysql - 比较mysql触发器中的字符串

lua - 获取表项索引

php - 如何在 PHP 中的对象中间插入一个项目?

mysql - 根据列值更改结果顺序?

php - 有没有更好的方法在 PHP/MySQL 中创建字母分页索引?

mysql - MySQL触发语法错误

c++ - 插入的最有效数据结构,然后按不同条件排序