0

I have two tables say table1 and table2.

fields of table1 - id and count
fields of table2 -  id and count

both tables have same fields. Now I want to create BEFORE INSERT TRIGGER on table1 which will check if count = 2 then insert into table2 otherwise in table1.

I created the trigger but when I fire this query ..example-

insert into table1 (id, count) values (1323, 2);

then one row is inserted into table2 (this I want) and same row is inserted into table1 also.

I want row should be inserted in table1 or table not in both tables.

what I do to achieve this ?

4

2 回答 2

0

试试这个:

delimiter $$
CREATE TRIGGER myTrigger
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
IF NEW.count = 2 THEN
insert into table2 (id, count) values (New.id,New.Count);
ELSE
<<no action>>
END IF;
END$$
于 2013-02-19T07:13:34.917 回答
0

我不确定你为什么想要这个,所以我怀疑我可能会就某种应该以不同方式修复的解决方案提供建议,但我们开始吧。

正如您在这个问题中看到的那样,不可能巧妙地停止插入。你可以尝试犯一个错误,这样你就不会真正插入,但我认为这真的很痛苦。

您可以做的是制作一个假表dummytable并将插入触发器放在那里。您的行将始终插入虚拟表中,但您可以将其插入table1table2根据您的意愿插入。触发器的肉看起来像

IF NEW.count = 2 THEN
INSERT INTO table2 (id, count) VALUES (New.id,New.Count);
ELSE
INSERT INTO table2 (id, count) VALUES (New.id,New.Count);
END IF;

您必须时不时地清洁虚拟台。

于 2013-02-19T08:05:32.087 回答