[英]How to create MySQL trigger to copy newly inserted data in one table to another
我有3個MySQL表:table1,table2 table3。 我試圖從table1和table2中提取特定的內容,然后通過使用觸發器將此提取的內容插入到table3中。 每當數據插入到table1中時,我都希望觸發器插入此新記錄
CREATE trigger 'test_trigger' after insert on 'table1'
select a.fname, a.lname,b.address,b.contact
from table1 a
inner join table2
on a.table1_id=b.table2_id
insert into table3(fname,lname,address,contact)
END;
INSERT語句可以插入SELECT語句選擇的值:
insert into table3(fname, lname, address, contact)
select a.fname, a.lname, b.address, b.contact
from table1 a
inner join table2
on a.table1_id = b.table2_id
請注意,您可能希望WHERE子句限制每次插入的數據量。 按照書面說明,每當將任何行插入到Table1中時,兩個表中的所有可聯接數據都將插入到Table3中。
CREATE trigger 'test_trigger' after insert on 'table1'
insert into table3 (fname, lname, address, contact)
select a.fname, a.lname,b.address,b.contact
from table1 a
inner join table2 on a.table1_id=b.table2_id
where a.id = NEW.id
END;
未經測試,但應該可以工作...觸發器中有OLD和NEW,它們可以像表別名一樣使用(例如a),對於插入,您只有NEW,對於更新NEW和OLD,對於刪除OLD
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.