[英]Pull one column from source table to another table after every insert into the destination table in MySQL 5.6 using a trigger
[英]Trying to pull the Last updated row_id from source table to another table after each insert into the destination table in MySQL 5.6 using a trigger
嗨,我有兩張桌子實驗和樣品。 我想創建一個觸發器,這樣每當我在 Sample 表中插入一行時,它應該拉取由 MySQL 在“Experiment”表中生成的最近的“Experiment_id”,並拉入名為“Experiment_id”的“Sample”表的列中。
EXPERIMENT TABLE
Experiment_id(auto_incremented) Exp_name
1 abc
SAMPLE TABLE
Sample_id Experiment_id sample_name
1 1
2 1
3 1
4 1
5 1
6 1
**New Entry Exp name - xyz**
EXPERIMENT TABLE
Experiment_id(auto_incremented) Exp_name
1 abc
2 xyz
SAMPLE TABLE
Sample_id Experiment_id sample_name
1 1
2 1
3 1
4 1
5 1
6 1
7 2
8 2
9 2
10 2
因此,當“Experiment”表中僅存在“Experiment_id”1 時生成 Sample_id“7-10”,當 MySQL 自動生成experiment_id 2 時生成 Sample_id“7-10”。
我正在使用 mysql 5.6。 請哪位大神幫幫我,謝謝!!
您將不得不同時使用觸發器來跟蹤插入和更新:
DROP TRIGGER IF EXISTS trigger_experiment_after_insert;
DELIMITER $$
CREATE TRIGGER trigger_experiment_after_insert
AFTER INSERT ON experiment FOR EACH ROW
BEGIN
-- sample_id will be auto_increment
INSERT INTO sample_log SET experiment_id = NEW.experiment_id;
END; $$
DELIMITER ;
使用更新觸發器來跟蹤更新:
DROP TRIGGER IF EXISTS trigger_experiment_after_update;
DELIMITER $$
CREATE TRIGGER trigger_experiment_after_update
AFTER UPDATE ON experiment FOR EACH ROW
BEGIN
-- sample_id will be auto_increment
INSERT INTO sample_log SET experiment_id = OLD.experiment_id;
END; $$
DELIMITER ;
我不會為此使用觸發器。 只需在 INSERT 語句中使用子查詢:
INSERT INTO SAMPLE (sample_name, Experiment_id) VALUES (
'sample name',
(SELECT MAX(Experiment_id) FROM EXPERIMENT)
)
如果你想用觸發器來做,試試這個:
create trigger SAMPLE_before_insert before insert on SAMPLE FOR EACH ROW
set new.Experiment_id = (select max(Experiment_id) from EXPERIMENT);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.