所以我有两张这样的桌子......
ext_words
-------------
| id | word |
-------------
| 1 | this |
-------------
| 2 | that |
-------------
| 3 | this |
-------------
ext_words_count
---------------------
| id | word | count |
---------------------
| 1 | this | 2 |
---------------------
| 2 | that | 1 |
---------------------
我正在尝试创建一个触发器:
ext_words_count.count
时ext_words.word
。 使事情进一步复杂化,
ext_words.word
更新时ext_words_count
中不存在ext_words
,我希望将其插入ext_words_count
并将count
设置为1。 / LI>
我一直在寻找类似的问题:
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
。在更新查询中是否有我遗漏的内容..?
答案 0 :(得分:38)
在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;
答案 1 :(得分:4)
避免使用像count这样的关键字,因为sql方法使用了它 一段时间它的创建错误,但有些运行良好
DELIMITER $$
CREATE TRIGGER update_count
AFTER UPDATE ON ext_words
FOR EACH ROW
BEGIN
SELECT count INTO @x FROM ext_words_count LIMIT 1;
UPDATE ext_words_count
SET count = @x + 1
WHERE word = NEW.word;
END;
$$
DELIMITER ;